Debian Codegraph @

src/backend/utils/cache/lsyscache.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * lsyscache.c
4 * Convenience routines for common queries in the system catalog cache.
5 *
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 * IDENTIFICATION
10 * src/backend/utils/cache/lsyscache.c
11 *
12 * NOTES
13 * Eventually, the index information should go through here, too.
14 *-------------------------------------------------------------------------
15 */
16 #include "postgres.h"
17
18 #include "access/hash.h"
19 #include "access/htup_details.h"
20 #include "bootstrap/bootstrap.h"
21 #include "catalog/namespace.h"
22 #include "catalog/pg_am.h"
23 #include "catalog/pg_amop.h"
24 #include "catalog/pg_amproc.h"
25 #include "catalog/pg_cast.h"
26 #include "catalog/pg_class.h"
27 #include "catalog/pg_collation.h"
28 #include "catalog/pg_constraint.h"
29 #include "catalog/pg_index.h"
30 #include "catalog/pg_language.h"
31 #include "catalog/pg_namespace.h"
32 #include "catalog/pg_opclass.h"
33 #include "catalog/pg_opfamily.h"
34 #include "catalog/pg_operator.h"
35 #include "catalog/pg_proc.h"
36 #include "catalog/pg_publication.h"
37 #include "catalog/pg_range.h"
38 #include "catalog/pg_statistic.h"
39 #include "catalog/pg_subscription.h"
40 #include "catalog/pg_transform.h"
41 #include "catalog/pg_type.h"
42 #include "miscadmin.h"
43 #include "nodes/makefuncs.h"
44 #include "utils/array.h"
45 #include "utils/builtins.h"
46 #include "utils/catcache.h"
47 #include "utils/datum.h"
48 #include "utils/fmgroids.h"
49 #include "utils/lsyscache.h"
50 #include "utils/syscache.h"
51 #include "utils/typcache.h"
52
53 /* Hook for plugins to get control in get_attavgwidth() */
54 get_attavgwidth_hook_type get_attavgwidth_hook = NULL;
55
56
57 /* ---------- AMOP CACHES ---------- */
58
59 /*
60 * op_in_opfamily
61 *
62 * Return t iff operator 'opno' is in operator family 'opfamily'.
63 *
64 * This function only considers search operators, not ordering operators.
65 */
66 bool
67 op_in_opfamily(Oid opno, Oid opfamily)
68 {
69 return SearchSysCacheExists3(AMOPOPID,
70 ObjectIdGetDatum(opno),
71 CharGetDatum(AMOP_SEARCH),
72 ObjectIdGetDatum(opfamily));
73 }
74
75 /*
76 * get_op_opfamily_strategy
77 *
78 * Get the operator's strategy number within the specified opfamily,
79 * or 0 if it's not a member of the opfamily.
80 *
81 * This function only considers search operators, not ordering operators.
82 */
83 int
84 get_op_opfamily_strategy(Oid opno, Oid opfamily)
85 {
86 HeapTuple tp;
87 Form_pg_amop amop_tup;
88 int result;
89
90 tp = SearchSysCache3(AMOPOPID,
91 ObjectIdGetDatum(opno),
92 CharGetDatum(AMOP_SEARCH),
93 ObjectIdGetDatum(opfamily));
94 if (!HeapTupleIsValid(tp))
95 return 0;
96 amop_tup = (Form_pg_amop) GETSTRUCT(tp);
97 result = amop_tup->amopstrategy;
98 ReleaseSysCache(tp);
99 return result;
100 }
101
102 /*
103 * get_op_opfamily_sortfamily
104 *
105 * If the operator is an ordering operator within the specified opfamily,
106 * return its amopsortfamily OID; else return InvalidOid.
107 */
108 Oid
109 get_op_opfamily_sortfamily(Oid opno, Oid opfamily)
110 {
111 HeapTuple tp;
112 Form_pg_amop amop_tup;
113 Oid result;
114
115 tp = SearchSysCache3(AMOPOPID,
116 ObjectIdGetDatum(opno),
117 CharGetDatum(AMOP_ORDER),
118 ObjectIdGetDatum(opfamily));
119 if (!HeapTupleIsValid(tp))
120 return InvalidOid;
121 amop_tup = (Form_pg_amop) GETSTRUCT(tp);
122 result = amop_tup->amopsortfamily;
123 ReleaseSysCache(tp);
124 return result;
125 }
126
127 /*
128 * get_op_opfamily_properties
129 *
130 * Get the operator's strategy number and declared input data types
131 * within the specified opfamily.
132 *
133 * Caller should already have verified that opno is a member of opfamily,
134 * therefore we raise an error if the tuple is not found.
135 */
136 void
137 get_op_opfamily_properties(Oid opno, Oid opfamily, bool ordering_op,
138 int *strategy,
139 Oid *lefttype,
140 Oid *righttype)
141 {
142 HeapTuple tp;
143 Form_pg_amop amop_tup;
144
145 tp = SearchSysCache3(AMOPOPID,
146 ObjectIdGetDatum(opno),
147 CharGetDatum(ordering_op ? AMOP_ORDER : AMOP_SEARCH),
148 ObjectIdGetDatum(opfamily));
149 if (!HeapTupleIsValid(tp))
150 elog(ERROR, "operator %u is not a member of opfamily %u",
151 opno, opfamily);
152 amop_tup = (Form_pg_amop) GETSTRUCT(tp);
153 *strategy = amop_tup->amopstrategy;
154 *lefttype = amop_tup->amoplefttype;
155 *righttype = amop_tup->amoprighttype;
156 ReleaseSysCache(tp);
157 }
158
159 /*
160 * get_opfamily_member
161 * Get the OID of the operator that implements the specified strategy
162 * with the specified datatypes for the specified opfamily.
163 *
164 * Returns InvalidOid if there is no pg_amop entry for the given keys.
165 */
166 Oid
167 get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype,
168 int16 strategy)
169 {
170 HeapTuple tp;
171 Form_pg_amop amop_tup;
172 Oid result;
173
174 tp = SearchSysCache4(AMOPSTRATEGY,
175 ObjectIdGetDatum(opfamily),
176 ObjectIdGetDatum(lefttype),
177 ObjectIdGetDatum(righttype),
178 Int16GetDatum(strategy));
179 if (!HeapTupleIsValid(tp))
180 return InvalidOid;
181 amop_tup = (Form_pg_amop) GETSTRUCT(tp);
182 result = amop_tup->amopopr;
183 ReleaseSysCache(tp);
184 return result;
185 }
186
187 /*
188 * get_opfamily_member_for_cmptype
189 * Get the OID of the operator that implements the specified comparison
190 * type with the specified datatypes for the specified opfamily.
191 *
192 * Returns InvalidOid if there is no mapping for the comparison type or no
193 * pg_amop entry for the given keys.
194 */
195 Oid
196 get_opfamily_member_for_cmptype(Oid opfamily, Oid lefttype, Oid righttype,
197 CompareType cmptype)
198 {
199 Oid opmethod;
200 StrategyNumber strategy;
201
202 opmethod = get_opfamily_method(opfamily);
203 strategy = IndexAmTranslateCompareType(cmptype, opmethod, opfamily, true);
204 if (!strategy)
205 return InvalidOid;
206 return get_opfamily_member(opfamily, lefttype, righttype, strategy);
207 }
208
209 /*
210 * get_opmethod_canorder
211 * Return amcanorder field for given index AM.
212 *
213 * To speed things up in the common cases, we're hardcoding the results from
214 * the built-in index types. Note that we also need to hardcode the negative
215 * results from the built-in non-btree index types, since you'll usually get a
216 * few hits for those as well. It would be nice to organize and cache this a
217 * bit differently to avoid the hardcoding.
218 */
219 static bool
220 get_opmethod_canorder(Oid amoid)
221 {
222 switch (amoid)
223 {
224 case BTREE_AM_OID:
225 return true;
226 case HASH_AM_OID:
227 case GIST_AM_OID:
228 case GIN_AM_OID:
229 case SPGIST_AM_OID:
230 case BRIN_AM_OID:
231 return false;
232 default:
233 {
234 bool result;
235 IndexAmRoutine *amroutine = GetIndexAmRoutineByAmId(amoid, false);
236
237 result = amroutine->amcanorder;
238 pfree(amroutine);
239 return result;
240 }
241 }
242 }
243
244 /*
245 * get_ordering_op_properties
246 * Given the OID of an ordering operator (a "<" or ">" operator),
247 * determine its opfamily, its declared input datatype, and its
248 * comparison type.
249 *
250 * Returns true if successful, false if no matching pg_amop entry exists.
251 * (This indicates that the operator is not a valid ordering operator.)
252 *
253 * Note: the operator could be registered in multiple families, for example
254 * if someone were to build a "reverse sort" opfamily. This would result in
255 * uncertainty as to whether "ORDER BY USING op" would default to NULLS FIRST
256 * or NULLS LAST, as well as inefficient planning due to failure to match up
257 * pathkeys that should be the same. So we want a determinate result here.
258 * Because of the way the syscache search works, we'll use the interpretation
259 * associated with the opfamily with smallest OID, which is probably
260 * determinate enough. Since there is no longer any particularly good reason
261 * to build reverse-sort opfamilies, it doesn't seem worth expending any
262 * additional effort on ensuring consistency.
263 */
264 bool
265 get_ordering_op_properties(Oid opno,
266 Oid *opfamily, Oid *opcintype, CompareType *cmptype)
267 {
268 bool result = false;
269 CatCList *catlist;
270 int i;
271
272 /* ensure outputs are initialized on failure */
273 *opfamily = InvalidOid;
274 *opcintype = InvalidOid;
275 *cmptype = COMPARE_INVALID;
276
277 /*
278 * Search pg_amop to see if the target operator is registered as the "<"
279 * or ">" operator of any btree opfamily.
280 */
281 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno));
282
283 for (i = 0; i < catlist->n_members; i++)
284 {
285 HeapTuple tuple = &catlist->members[i]->tuple;
286 Form_pg_amop aform = (Form_pg_amop) GETSTRUCT(tuple);
287 CompareType am_cmptype;
288
289 /* must be ordering index */
290 if (!get_opmethod_canorder(aform->amopmethod))
291 continue;
292
293 am_cmptype = IndexAmTranslateStrategy(aform->amopstrategy,
294 aform->amopmethod,
295 aform->amopfamily,
296 true);
297
298 if (am_cmptype == COMPARE_LT || am_cmptype == COMPARE_GT)
299 {
300 /* Found it ... should have consistent input types */
301 if (aform->amoplefttype == aform->amoprighttype)
302 {
303 /* Found a suitable opfamily, return info */
304 *opfamily = aform->amopfamily;
305 *opcintype = aform->amoplefttype;
306 *cmptype = am_cmptype;
307 result = true;
308 break;
309 }
310 }
311 }
312
313 ReleaseSysCacheList(catlist);
314
315 return result;
316 }
317
318 /*
319 * get_equality_op_for_ordering_op
320 * Get the OID of the datatype-specific equality operator
321 * associated with an ordering operator (a "<" or ">" operator).
322 *
323 * If "reverse" isn't NULL, also set *reverse to false if the operator is "<",
324 * true if it's ">"
325 *
326 * Returns InvalidOid if no matching equality operator can be found.
327 * (This indicates that the operator is not a valid ordering operator.)
328 */
329 Oid
330 get_equality_op_for_ordering_op(Oid opno, bool *reverse)
331 {
332 Oid result = InvalidOid;
333 Oid opfamily;
334 Oid opcintype;
335 CompareType cmptype;
336
337 /* Find the operator in pg_amop */
338 if (get_ordering_op_properties(opno,
339 &opfamily, &opcintype, &cmptype))
340 {
341 /* Found a suitable opfamily, get matching equality operator */
342 result = get_opfamily_member_for_cmptype(opfamily,
343 opcintype,
344 opcintype,
345 COMPARE_EQ);
346 if (reverse)
347 *reverse = (cmptype == COMPARE_GT);
348 }
349
350 return result;
351 }
352
353 /*
354 * get_ordering_op_for_equality_op
355 * Get the OID of a datatype-specific "less than" ordering operator
356 * associated with an equality operator. (If there are multiple
357 * possibilities, assume any one will do.)
358 *
359 * This function is used when we have to sort data before unique-ifying,
360 * and don't much care which sorting op is used as long as it's compatible
361 * with the intended equality operator. Since we need a sorting operator,
362 * it should be single-data-type even if the given operator is cross-type.
363 * The caller specifies whether to find an op for the LHS or RHS data type.
364 *
365 * Returns InvalidOid if no matching ordering operator can be found.
366 */
367 Oid
368 get_ordering_op_for_equality_op(Oid opno, bool use_lhs_type)
369 {
370 Oid result = InvalidOid;
371 CatCList *catlist;
372 int i;
373
374 /*
375 * Search pg_amop to see if the target operator is registered as the "="
376 * operator of any btree opfamily.
377 */
378 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno));
379
380 for (i = 0; i < catlist->n_members; i++)
381 {
382 HeapTuple tuple = &catlist->members[i]->tuple;
383 Form_pg_amop aform = (Form_pg_amop) GETSTRUCT(tuple);
384 CompareType cmptype;
385
386 /* must be ordering index */
387 if (!get_opmethod_canorder(aform->amopmethod))
388 continue;
389
390 cmptype = IndexAmTranslateStrategy(aform->amopstrategy,
391 aform->amopmethod,
392 aform->amopfamily,
393 true);
394 if (cmptype == COMPARE_EQ)
395 {
396 /* Found a suitable opfamily, get matching ordering operator */
397 Oid typid;
398
399 typid = use_lhs_type ? aform->amoplefttype : aform->amoprighttype;
400 result = get_opfamily_member_for_cmptype(aform->amopfamily,
401 typid, typid,
402 COMPARE_LT);
403 if (OidIsValid(result))
404 break;
405 /* failure probably shouldn't happen, but keep looking if so */
406 }
407 }
408
409 ReleaseSysCacheList(catlist);
410
411 return result;
412 }
413
414 /*
415 * get_mergejoin_opfamilies
416 * Given a putatively mergejoinable operator, return a list of the OIDs
417 * of the amcanorder opfamilies in which it represents equality.
418 *
419 * It is possible (though at present unusual) for an operator to be equality
420 * in more than one opfamily, hence the result is a list. This also lets us
421 * return NIL if the operator is not found in any opfamilies.
422 *
423 * The planner currently uses simple equal() tests to compare the lists
424 * returned by this function, which makes the list order relevant, though
425 * strictly speaking it should not be. Because of the way syscache list
426 * searches are handled, in normal operation the result will be sorted by OID
427 * so everything works fine. If running with system index usage disabled,
428 * the result ordering is unspecified and hence the planner might fail to
429 * recognize optimization opportunities ... but that's hardly a scenario in
430 * which performance is good anyway, so there's no point in expending code
431 * or cycles here to guarantee the ordering in that case.
432 */
433 List *
434 get_mergejoin_opfamilies(Oid opno)
435 {
436 List *result = NIL;
437 CatCList *catlist;
438 int i;
439
440 /*
441 * Search pg_amop to see if the target operator is registered as the "="
442 * operator of any opfamily of an ordering index type.
443 */
444 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno));
445
446 for (i = 0; i < catlist->n_members; i++)
447 {
448 HeapTuple tuple = &catlist->members[i]->tuple;
449 Form_pg_amop aform = (Form_pg_amop) GETSTRUCT(tuple);
450
451 /* must be ordering index equality */
452 if (get_opmethod_canorder(aform->amopmethod) &&
453 IndexAmTranslateStrategy(aform->amopstrategy,
454 aform->amopmethod,
455 aform->amopfamily,
456 true) == COMPARE_EQ)
457 result = lappend_oid(result, aform->amopfamily);
458 }
459
460 ReleaseSysCacheList(catlist);
461
462 return result;
463 }
464
465 /*
466 * get_compatible_hash_operators
467 * Get the OID(s) of hash equality operator(s) compatible with the given
468 * operator, but operating on its LHS and/or RHS datatype.
469 *
470 * An operator for the LHS type is sought and returned into *lhs_opno if
471 * lhs_opno isn't NULL. Similarly, an operator for the RHS type is sought
472 * and returned into *rhs_opno if rhs_opno isn't NULL.
473 *
474 * If the given operator is not cross-type, the results should be the same
475 * operator, but in cross-type situations they will be different.
476 *
477 * Returns true if able to find the requested operator(s), false if not.
478 * (This indicates that the operator should not have been marked oprcanhash.)
479 *
480 * Callers must beware that for container types (arrays, records, ranges)
481 * this function will succeed for array_eq etc, but the hash function could
482 * fail at runtime if the contained type(s) are not hashable. If it is
483 * possible that the operator is one of these, precheck with op_hashjoinable
484 * or get_op_hash_functions_ext.
485 */
486 bool
487 get_compatible_hash_operators(Oid opno,
488 Oid *lhs_opno, Oid *rhs_opno)
489 {
490 bool result = false;
491 CatCList *catlist;
492 int i;
493
494 /* Ensure output args are initialized on failure */
495 if (lhs_opno)
496 *lhs_opno = InvalidOid;
497 if (rhs_opno)
498 *rhs_opno = InvalidOid;
499
500 /*
501 * Search pg_amop to see if the target operator is registered as the "="
502 * operator of any hash opfamily. If the operator is registered in
503 * multiple opfamilies, assume we can use any one.
504 */
505 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno));
506
507 for (i = 0; i < catlist->n_members; i++)
508 {
509 HeapTuple tuple = &catlist->members[i]->tuple;
510 Form_pg_amop aform = (Form_pg_amop) GETSTRUCT(tuple);
511
512 if (aform->amopmethod == HASH_AM_OID &&
513 aform->amopstrategy == HTEqualStrategyNumber)
514 {
515 /* No extra lookup needed if given operator is single-type */
516 if (aform->amoplefttype == aform->amoprighttype)
517 {
518 if (lhs_opno)
519 *lhs_opno = opno;
520 if (rhs_opno)
521 *rhs_opno = opno;
522 result = true;
523 break;
524 }
525
526 /*
527 * Get the matching single-type operator(s). Failure probably
528 * shouldn't happen --- it implies a bogus opfamily --- but
529 * continue looking if so.
530 */
531 if (lhs_opno)
532 {
533 *lhs_opno = get_opfamily_member(aform->amopfamily,
534 aform->amoplefttype,
535 aform->amoplefttype,
536 HTEqualStrategyNumber);
537 if (!OidIsValid(*lhs_opno))
538 continue;
539 /* Matching LHS found, done if caller doesn't want RHS */
540 if (!rhs_opno)
541 {
542 result = true;
543 break;
544 }
545 }
546 if (rhs_opno)
547 {
548 *rhs_opno = get_opfamily_member(aform->amopfamily,
549 aform->amoprighttype,
550 aform->amoprighttype,
551 HTEqualStrategyNumber);
552 if (!OidIsValid(*rhs_opno))
553 {
554 /* Forget any LHS operator from this opfamily */
555 if (lhs_opno)
556 *lhs_opno = InvalidOid;
557 continue;
558 }
559 /* Matching RHS found, so done */
560 result = true;
561 break;
562 }
563 }
564 }
565
566 ReleaseSysCacheList(catlist);
567
568 return result;
569 }
570
571 /*
572 * get_op_hash_functions
573 * Get the OID(s) of the standard hash support function(s) compatible with
574 * the given operator, operating on its LHS and/or RHS datatype as required.
575 *
576 * A function for the LHS type is sought and returned into *lhs_procno if
577 * lhs_procno isn't NULL. Similarly, a function for the RHS type is sought
578 * and returned into *rhs_procno if rhs_procno isn't NULL.
579 *
580 * If the given operator is not cross-type, the results should be the same
581 * function, but in cross-type situations they will be different.
582 *
583 * Returns true if able to find the requested function(s), false if not.
584 * (This indicates that the operator should not have been marked oprcanhash.)
585 *
586 * Callers must beware that for container types (arrays, records, ranges)
587 * this function will succeed for array_eq etc, but the hash function could
588 * fail at runtime if the contained type(s) are not hashable. If it is
589 * possible that the operator is one of these, use get_op_hash_functions_ext
590 * or precheck with op_hashjoinable.
591 */
592 bool
593 get_op_hash_functions(Oid opno,
594 RegProcedure *lhs_procno, RegProcedure *rhs_procno)
595 {
596 bool result = false;
597 CatCList *catlist;
598 int i;
599
600 /* Ensure output args are initialized on failure */
601 if (lhs_procno)
602 *lhs_procno = InvalidOid;
603 if (rhs_procno)
604 *rhs_procno = InvalidOid;
605
606 /*
607 * Search pg_amop to see if the target operator is registered as the "="
608 * operator of any hash opfamily. If the operator is registered in
609 * multiple opfamilies, assume we can use any one.
610 */
611 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno));
612
613 for (i = 0; i < catlist->n_members; i++)
614 {
615 HeapTuple tuple = &catlist->members[i]->tuple;
616 Form_pg_amop aform = (Form_pg_amop) GETSTRUCT(tuple);
617
618 if (aform->amopmethod == HASH_AM_OID &&
619 aform->amopstrategy == HTEqualStrategyNumber)
620 {
621 /*
622 * Get the matching support function(s). Failure probably
623 * shouldn't happen --- it implies a bogus opfamily --- but
624 * continue looking if so.
625 */
626 if (lhs_procno)
627 {
628 *lhs_procno = get_opfamily_proc(aform->amopfamily,
629 aform->amoplefttype,
630 aform->amoplefttype,
631 HASHSTANDARD_PROC);
632 if (!OidIsValid(*lhs_procno))
633 continue;
634 /* Matching LHS found, done if caller doesn't want RHS */
635 if (!rhs_procno)
636 {
637 result = true;
638 break;
639 }
640 /* Only one lookup needed if given operator is single-type */
641 if (aform->amoplefttype == aform->amoprighttype)
642 {
643 *rhs_procno = *lhs_procno;
644 result = true;
645 break;
646 }
647 }
648 if (rhs_procno)
649 {
650 *rhs_procno = get_opfamily_proc(aform->amopfamily,
651 aform->amoprighttype,
652 aform->amoprighttype,
653 HASHSTANDARD_PROC);
654 if (!OidIsValid(*rhs_procno))
655 {
656 /* Forget any LHS function from this opfamily */
657 if (lhs_procno)
658 *lhs_procno = InvalidOid;
659 continue;
660 }
661 /* Matching RHS found, so done */
662 result = true;
663 break;
664 }
665 }
666 }
667
668 ReleaseSysCacheList(catlist);
669
670 return result;
671 }
672
673 /*
674 * get_op_hash_functions_ext
675 * As above, but verify hashability in container-type cases.
676 *
677 * As with op_hashjoinable, assume the left input type is sufficient
678 * to disambiguate container-type cases.
679 */
680 bool
681 get_op_hash_functions_ext(Oid opno, Oid inputtype,
682 RegProcedure *lhs_procno, RegProcedure *rhs_procno)
683 {
684 TypeCacheEntry *typentry;
685
686 /* Ensure output args are initialized on failure */
687 if (lhs_procno)
688 *lhs_procno = InvalidOid;
689 if (rhs_procno)
690 *rhs_procno = InvalidOid;
691
692 /* As in op_hashjoinable, let the typcache handle the hard cases */
693 if (opno == ARRAY_EQ_OP)
694 {
695 typentry = lookup_type_cache(inputtype, TYPECACHE_HASH_PROC);
696 if (typentry->hash_proc != F_HASH_ARRAY)
697 return false;
698 }
699 else if (opno == RECORD_EQ_OP)
700 {
701 typentry = lookup_type_cache(inputtype, TYPECACHE_HASH_PROC);
702 if (typentry->hash_proc != F_HASH_RECORD)
703 return false;
704 }
705 else if (opno == RANGE_EQ_OP)
706 {
707 typentry = lookup_type_cache(inputtype, TYPECACHE_HASH_PROC);
708 if (typentry->hash_proc != F_HASH_RANGE)
709 return false;
710 }
711 else if (opno == MULTIRANGE_EQ_OP)
712 {
713 typentry = lookup_type_cache(inputtype, TYPECACHE_HASH_PROC);
714 if (typentry->hash_proc != F_HASH_MULTIRANGE)
715 return false;
716 }
717
718 /* OK, do the normal lookup */
719 return get_op_hash_functions(opno, lhs_procno, rhs_procno);
720 }
721
722 /*
723 * get_op_index_interpretation
724 * Given an operator's OID, find out which amcanorder opfamilies it belongs to,
725 * and what properties it has within each one. The results are returned
726 * as a palloc'd list of OpIndexInterpretation structs.
727 *
728 * In addition to the normal btree operators, we consider a <> operator to be
729 * a "member" of an opfamily if its negator is an equality operator of the
730 * opfamily. COMPARE_NE is returned as the strategy number for this case.
731 */
732 List *
733 get_op_index_interpretation(Oid opno)
734 {
735 List *result = NIL;
736 OpIndexInterpretation *thisresult;
737 CatCList *catlist;
738 int i;
739
740 /*
741 * Find all the pg_amop entries containing the operator.
742 */
743 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno));
744
745 for (i = 0; i < catlist->n_members; i++)
746 {
747 HeapTuple op_tuple = &catlist->members[i]->tuple;
748 Form_pg_amop op_form = (Form_pg_amop) GETSTRUCT(op_tuple);
749 CompareType cmptype;
750
751 /* must be ordering index */
752 if (!get_opmethod_canorder(op_form->amopmethod))
753 continue;
754
755 /* Get the operator's comparision type */
756 cmptype = IndexAmTranslateStrategy(op_form->amopstrategy,
757 op_form->amopmethod,
758 op_form->amopfamily,
759 true);
760
761 /* should not happen */
762 if (cmptype == COMPARE_INVALID)
763 continue;
764
765 thisresult = (OpIndexInterpretation *)
766 palloc(sizeof(OpIndexInterpretation));
767 thisresult->opfamily_id = op_form->amopfamily;
768 thisresult->cmptype = cmptype;
769 thisresult->oplefttype = op_form->amoplefttype;
770 thisresult->oprighttype = op_form->amoprighttype;
771 result = lappend(result, thisresult);
772 }
773
774 ReleaseSysCacheList(catlist);
775
776 /*
777 * If we didn't find any btree opfamily containing the operator, perhaps
778 * it is a <> operator. See if it has a negator that is in an opfamily.
779 */
780 if (result == NIL)
781 {
782 Oid op_negator = get_negator(opno);
783
784 if (OidIsValid(op_negator))
785 {
786 catlist = SearchSysCacheList1(AMOPOPID,
787 ObjectIdGetDatum(op_negator));
788
789 for (i = 0; i < catlist->n_members; i++)
790 {
791 HeapTuple op_tuple = &catlist->members[i]->tuple;
792 Form_pg_amop op_form = (Form_pg_amop) GETSTRUCT(op_tuple);
793 IndexAmRoutine *amroutine = GetIndexAmRoutineByAmId(op_form->amopmethod, false);
794 CompareType cmptype;
795
796 /* must be ordering index */
797 if (!amroutine->amcanorder)
798 continue;
799
800 /* Get the operator's comparision type */
801 cmptype = IndexAmTranslateStrategy(op_form->amopstrategy,
802 op_form->amopmethod,
803 op_form->amopfamily,
804 true);
805
806 /* Only consider negators that are = */
807 if (cmptype != COMPARE_EQ)
808 continue;
809
810 /* OK, report it as COMPARE_NE */
811 thisresult = (OpIndexInterpretation *)
812 palloc(sizeof(OpIndexInterpretation));
813 thisresult->opfamily_id = op_form->amopfamily;
814 thisresult->cmptype = COMPARE_NE;
815 thisresult->oplefttype = op_form->amoplefttype;
816 thisresult->oprighttype = op_form->amoprighttype;
817 result = lappend(result, thisresult);
818 }
819
820 ReleaseSysCacheList(catlist);
821 }
822 }
823
824 return result;
825 }
826
827 /*
828 * equality_ops_are_compatible
829 * Return true if the two given operators have compatible equality
830 * semantics.
831 *
832 * This is trivially true if they are the same operator. Otherwise,
833 * we look to see if they both belong to an opfamily that guarantees
834 * compatible semantics for equality. Either finding allows us to assume
835 * that they have compatible notions of equality.
836 *
837 * The typical use is to compare two equality operators (for instance the
838 * cross-type operators int24eq vs int4eq), but the test is meaningful for
839 * any pair of operators in a btree/hash opfamily. Btree marks its
840 * opfamilies as amconsistentequality, which guarantees that every member
841 * of the family (=, <, <=, >, >=) agrees on the equivalence relation
842 * defined by the family's "=". So a non-equality operator and an
843 * equality operator from the same opfamily are also "compatible" in this
844 * sense.
845 */
846 bool
847 equality_ops_are_compatible(Oid opno1, Oid opno2)
848 {
849 bool result;
850 CatCList *catlist;
851 int i;
852
853 /* Easy if they're the same operator */
854 if (opno1 == opno2)
855 return true;
856
857 /*
858 * We search through all the pg_amop entries for opno1.
859 */
860 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno1));
861
862 result = false;
863 for (i = 0; i < catlist->n_members; i++)
864 {
865 HeapTuple op_tuple = &catlist->members[i]->tuple;
866 Form_pg_amop op_form = (Form_pg_amop) GETSTRUCT(op_tuple);
867
868 /*
869 * op_in_opfamily() is cheaper than GetIndexAmRoutineByAmId(), so
870 * check it first
871 */
872 if (op_in_opfamily(opno2, op_form->amopfamily))
873 {
874 IndexAmRoutine *amroutine = GetIndexAmRoutineByAmId(op_form->amopmethod, false);
875
876 if (amroutine->amconsistentequality)
877 {
878 result = true;
879 break;
880 }
881 }
882 }
883
884 ReleaseSysCacheList(catlist);
885
886 return result;
887 }
888
889 /*
890 * comparison_ops_are_compatible
891 * Return true if the two given comparison operators have compatible
892 * semantics.
893 *
894 * This is trivially true if they are the same operator. Otherwise, we look
895 * to see if they both belong to an opfamily that guarantees compatible
896 * semantics for ordering. (For example, for btree, '<' and '>=' ops match if
897 * they belong to the same family.)
898 *
899 * (This is identical to equality_ops_are_compatible(), except that we check
900 * amconsistentordering instead of amconsistentequality.)
901 */
902 bool
903 comparison_ops_are_compatible(Oid opno1, Oid opno2)
904 {
905 bool result;
906 CatCList *catlist;
907 int i;
908
909 /* Easy if they're the same operator */
910 if (opno1 == opno2)
911 return true;
912
913 /*
914 * We search through all the pg_amop entries for opno1.
915 */
916 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno1));
917
918 result = false;
919 for (i = 0; i < catlist->n_members; i++)
920 {
921 HeapTuple op_tuple = &catlist->members[i]->tuple;
922 Form_pg_amop op_form = (Form_pg_amop) GETSTRUCT(op_tuple);
923
924 /*
925 * op_in_opfamily() is cheaper than GetIndexAmRoutineByAmId(), so
926 * check it first
927 */
928 if (op_in_opfamily(opno2, op_form->amopfamily))
929 {
930 IndexAmRoutine *amroutine = GetIndexAmRoutineByAmId(op_form->amopmethod, false);
931
932 if (amroutine->amconsistentordering)
933 {
934 result = true;
935 break;
936 }
937 }
938 }
939
940 ReleaseSysCacheList(catlist);
941
942 return result;
943 }
944
945 /*
946 * collations_agree_on_equality
947 * Return true if the two collations have equivalent notions of equality,
948 * so that a uniqueness or equality proof established under one side
949 * carries over to a comparison performed under the other side.
950 *
951 * Note: this is equality compatibility only. Do NOT use this to reason
952 * about ordering.
953 *
954 * An InvalidOid on either side denotes the absence of a collation -- that
955 * side's operation is not collation-sensitive (e.g. a non-collatable column
956 * type). Absence of a collation cannot conflict with the other side's
957 * collation, so we treat such pairs as agreeing on equality. This generalizes
958 * the asymmetric treatment in IndexCollMatchesExprColl().
959 *
960 * Otherwise the collations have equivalent equality if they match, or if both
961 * are deterministic: by definition a deterministic collation treats two
962 * strings as equal iff they are byte-wise equal (see CREATE COLLATION), so any
963 * two deterministic collations share the same equality relation. A mismatch
964 * involving a nondeterministic collation, however, may mean the two equality
965 * relations disagree, and the proof is unsound.
966 */
967 bool
968 collations_agree_on_equality(Oid coll1, Oid coll2)
969 {
970 if (!OidIsValid(coll1) || !OidIsValid(coll2))
971 return true;
972
973 if (coll1 == coll2)
974 return true;
975
976 if (!get_collation_isdeterministic(coll1) ||
977 !get_collation_isdeterministic(coll2))
978 return false;
979
980 return true;
981 }
982
983 /*
984 * op_is_safe_index_member
985 * Check if the operator is a member of a B-tree or Hash operator family.
986 *
987 * Membership in such an opfamily has several useful implications: the operator
988 * returns non-null for non-null inputs (i.e. "null-safety", required so that
989 * the operator doesn't break index integrity), and it agrees with other
990 * members of the same opfamily on equality semantics. Callers use this check
991 * as a proxy for any of those properties.
992 */
993 bool
994 op_is_safe_index_member(Oid opno)
995 {
996 bool result = false;
997 CatCList *catlist;
998 int i;
999
1000 /*
1001 * Search pg_amop to see if the target operator is registered for any
1002 * btree or hash opfamily.
1003 */
1004 catlist = SearchSysCacheList1(AMOPOPID, ObjectIdGetDatum(opno));
1005
1006 for (i = 0; i < catlist->n_members; i++)
1007 {
1008 HeapTuple tuple = &catlist->members[i]->tuple;
1009 Form_pg_amop aform = (Form_pg_amop) GETSTRUCT(tuple);
1010
1011 /* Check if the AM is B-tree or Hash */
1012 if (aform->amopmethod == BTREE_AM_OID ||
1013 aform->amopmethod == HASH_AM_OID)
1014 {
1015 result = true;
1016 break;
1017 }
1018 }
1019
1020 ReleaseSysCacheList(catlist);
1021
1022 return result;
1023 }
1024
1025
1026 /* ---------- AMPROC CACHES ---------- */
1027
1028 /*
1029 * get_opfamily_proc
1030 * Get the OID of the specified support function
1031 * for the specified opfamily and datatypes.
1032 *
1033 * Returns InvalidOid if there is no pg_amproc entry for the given keys.
1034 */
1035 Oid
1036 get_opfamily_proc(Oid opfamily, Oid lefttype, Oid righttype, int16 procnum)
1037 {
1038 HeapTuple tp;
1039 Form_pg_amproc amproc_tup;
1040 RegProcedure result;
1041
1042 tp = SearchSysCache4(AMPROCNUM,
1043 ObjectIdGetDatum(opfamily),
1044 ObjectIdGetDatum(lefttype),
1045 ObjectIdGetDatum(righttype),
1046 Int16GetDatum(procnum));
1047 if (!HeapTupleIsValid(tp))
1048 return InvalidOid;
1049 amproc_tup = (Form_pg_amproc) GETSTRUCT(tp);
1050 result = amproc_tup->amproc;
1051 ReleaseSysCache(tp);
1052 return result;
1053 }
1054
1055
1056 /* ---------- ATTRIBUTE CACHES ---------- */
1057
1058 /*
1059 * get_attname
1060 * Given the relation id and the attribute number, return the "attname"
1061 * field from the attribute relation as a palloc'ed string.
1062 *
1063 * If no such attribute exists and missing_ok is true, NULL is returned;
1064 * otherwise a not-intended-for-user-consumption error is thrown.
1065 */
1066 char *
1067 get_attname(Oid relid, AttrNumber attnum, bool missing_ok)
1068 {
1069 HeapTuple tp;
1070
1071 tp = SearchSysCache2(ATTNUM,
1072 ObjectIdGetDatum(relid), Int16GetDatum(attnum));
1073 if (HeapTupleIsValid(tp))
1074 {
1075 Form_pg_attribute att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1076 char *result;
1077
1078 result = pstrdup(NameStr(att_tup->attname));
1079 ReleaseSysCache(tp);
1080 return result;
1081 }
1082
1083 if (!missing_ok)
1084 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1085 attnum, relid);
1086 return NULL;
1087 }
1088
1089 /*
1090 * get_attnum
1091 *
1092 * Given the relation id and the attribute name,
1093 * return the "attnum" field from the attribute relation.
1094 *
1095 * Returns InvalidAttrNumber if the attr doesn't exist (or is dropped).
1096 */
1097 AttrNumber
1098 get_attnum(Oid relid, const char *attname)
1099 {
1100 HeapTuple tp;
1101
1102 tp = SearchSysCacheAttName(relid, attname);
1103 if (HeapTupleIsValid(tp))
1104 {
1105 Form_pg_attribute att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1106 AttrNumber result;
1107
1108 result = att_tup->attnum;
1109 ReleaseSysCache(tp);
1110 return result;
1111 }
1112 else
1113 return InvalidAttrNumber;
1114 }
1115
1116 /*
1117 * get_attgenerated
1118 *
1119 * Given the relation id and the attribute number,
1120 * return the "attgenerated" field from the attribute relation.
1121 *
1122 * Errors if not found.
1123 *
1124 * Since not generated is represented by '\0', this can also be used as a
1125 * Boolean test.
1126 */
1127 char
1128 get_attgenerated(Oid relid, AttrNumber attnum)
1129 {
1130 HeapTuple tp;
1131 Form_pg_attribute att_tup;
1132 char result;
1133
1134 tp = SearchSysCache2(ATTNUM,
1135 ObjectIdGetDatum(relid),
1136 Int16GetDatum(attnum));
1137 if (!HeapTupleIsValid(tp))
1138 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1139 attnum, relid);
1140 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1141 result = att_tup->attgenerated;
1142 ReleaseSysCache(tp);
1143 return result;
1144 }
1145
1146 /*
1147 * get_atttype
1148 *
1149 * Given the relation OID and the attribute number with the relation,
1150 * return the attribute type OID.
1151 */
1152 Oid
1153 get_atttype(Oid relid, AttrNumber attnum)
1154 {
1155 HeapTuple tp;
1156
1157 tp = SearchSysCache2(ATTNUM,
1158 ObjectIdGetDatum(relid),
1159 Int16GetDatum(attnum));
1160 if (HeapTupleIsValid(tp))
1161 {
1162 Form_pg_attribute att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1163 Oid result;
1164
1165 result = att_tup->atttypid;
1166 ReleaseSysCache(tp);
1167 return result;
1168 }
1169 else
1170 return InvalidOid;
1171 }
1172
1173 /*
1174 * get_atttypetypmodcoll
1175 *
1176 * A three-fer: given the relation id and the attribute number,
1177 * fetch atttypid, atttypmod, and attcollation in a single cache lookup.
1178 *
1179 * Unlike the otherwise-similar get_atttype, this routine
1180 * raises an error if it can't obtain the information.
1181 */
1182 void
1183 get_atttypetypmodcoll(Oid relid, AttrNumber attnum,
1184 Oid *typid, int32 *typmod, Oid *collid)
1185 {
1186 HeapTuple tp;
1187 Form_pg_attribute att_tup;
1188
1189 tp = SearchSysCache2(ATTNUM,
1190 ObjectIdGetDatum(relid),
1191 Int16GetDatum(attnum));
1192 if (!HeapTupleIsValid(tp))
1193 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1194 attnum, relid);
1195 att_tup = (Form_pg_attribute) GETSTRUCT(tp);
1196
1197 *typid = att_tup->atttypid;
1198 *typmod = att_tup->atttypmod;
1199 *collid = att_tup->attcollation;
1200 ReleaseSysCache(tp);
1201 }
1202
1203 /*
1204 * get_attoptions
1205 *
1206 * Given the relation id and the attribute number,
1207 * return the attribute options text[] datum, if any.
1208 */
1209 Datum
1210 get_attoptions(Oid relid, int16 attnum)
1211 {
1212 HeapTuple tuple;
1213 Datum attopts;
1214 Datum result;
1215 bool isnull;
1216
1217 tuple = SearchSysCache2(ATTNUM,
1218 ObjectIdGetDatum(relid),
1219 Int16GetDatum(attnum));
1220
1221 if (!HeapTupleIsValid(tuple))
1222 elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1223 attnum, relid);
1224
1225 attopts = SysCacheGetAttr(ATTNAME, tuple, Anum_pg_attribute_attoptions,
1226 &isnull);
1227
1228 if (isnull)
1229 result = (Datum) 0;
1230 else
1231 result = datumCopy(attopts, false, -1); /* text[] */
1232
1233 ReleaseSysCache(tuple);
1234
1235 return result;
1236 }
1237
1238 /* ---------- PG_CAST CACHE ---------- */
1239
1240 /*
1241 * get_cast_oid - given two type OIDs, look up a cast OID
1242 *
1243 * If missing_ok is false, throw an error if the cast is not found. If
1244 * true, just return InvalidOid.
1245 */
1246 Oid
1247 get_cast_oid(Oid sourcetypeid, Oid targettypeid, bool missing_ok)
1248 {
1249 Oid oid;
1250
1251 oid = GetSysCacheOid2(CASTSOURCETARGET, Anum_pg_cast_oid,
1252 ObjectIdGetDatum(sourcetypeid),
1253 ObjectIdGetDatum(targettypeid));
1254 if (!OidIsValid(oid) && !missing_ok)
1255 ereport(ERROR,
1256 (errcode(ERRCODE_UNDEFINED_OBJECT),
1257 errmsg("cast from type %s to type %s does not exist",
1258 format_type_be(sourcetypeid),
1259 format_type_be(targettypeid))));
1260 return oid;
1261 }
1262
1263 /* ---------- COLLATION CACHE ---------- */
1264
1265 /*
1266 * get_collation_name
1267 * Returns the name of a given pg_collation entry.
1268 *
1269 * Returns a palloc'd copy of the string, or NULL if no such collation.
1270 *
1271 * NOTE: since collation name is not unique, be wary of code that uses this
1272 * for anything except preparing error messages.
1273 */
1274 char *
1275 get_collation_name(Oid colloid)
1276 {
1277 HeapTuple tp;
1278
1279 tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(colloid));
1280 if (HeapTupleIsValid(tp))
1281 {
1282 Form_pg_collation colltup = (Form_pg_collation) GETSTRUCT(tp);
1283 char *result;
1284
1285 result = pstrdup(NameStr(colltup->collname));
1286 ReleaseSysCache(tp);
1287 return result;
1288 }
1289 else
1290 return NULL;
1291 }
1292
1293 bool
1294 get_collation_isdeterministic(Oid colloid)
1295 {
1296 HeapTuple tp;
1297 Form_pg_collation colltup;
1298 bool result;
1299
1300 tp = SearchSysCache1(COLLOID, ObjectIdGetDatum(colloid));
1301 if (!HeapTupleIsValid(tp))
1302 elog(ERROR, "cache lookup failed for collation %u", colloid);
1303 colltup = (Form_pg_collation) GETSTRUCT(tp);
1304 result = colltup->collisdeterministic;
1305 ReleaseSysCache(tp);
1306 return result;
1307 }
1308
1309 /* ---------- CONSTRAINT CACHE ---------- */
1310
1311 /*
1312 * get_constraint_name
1313 * Returns the name of a given pg_constraint entry.
1314 *
1315 * Returns a palloc'd copy of the string, or NULL if no such constraint.
1316 *
1317 * NOTE: since constraint name is not unique, be wary of code that uses this
1318 * for anything except preparing error messages.
1319 */
1320 char *
1321 get_constraint_name(Oid conoid)
1322 {
1323 HeapTuple tp;
1324
1325 tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(conoid));
1326 if (HeapTupleIsValid(tp))
1327 {
1328 Form_pg_constraint contup = (Form_pg_constraint) GETSTRUCT(tp);
1329 char *result;
1330
1331 result = pstrdup(NameStr(contup->conname));
1332 ReleaseSysCache(tp);
1333 return result;
1334 }
1335 else
1336 return NULL;
1337 }
1338
1339 /*
1340 * get_constraint_index
1341 * Given the OID of a unique, primary-key, or exclusion constraint,
1342 * return the OID of the underlying index.
1343 *
1344 * Returns InvalidOid if the constraint could not be found or is of
1345 * the wrong type.
1346 *
1347 * The intent of this function is to return the index "owned" by the
1348 * specified constraint. Therefore we must check contype, since some
1349 * pg_constraint entries (e.g. for foreign-key constraints) store the
1350 * OID of an index that is referenced but not owned by the constraint.
1351 */
1352 Oid
1353 get_constraint_index(Oid conoid)
1354 {
1355 HeapTuple tp;
1356
1357 tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(conoid));
1358 if (HeapTupleIsValid(tp))
1359 {
1360 Form_pg_constraint contup = (Form_pg_constraint) GETSTRUCT(tp);
1361 Oid result;
1362
1363 if (contup->contype == CONSTRAINT_UNIQUE ||
1364 contup->contype == CONSTRAINT_PRIMARY ||
1365 contup->contype == CONSTRAINT_EXCLUSION)
1366 result = contup->conindid;
1367 else
1368 result = InvalidOid;
1369 ReleaseSysCache(tp);
1370 return result;
1371 }
1372 else
1373 return InvalidOid;
1374 }
1375
1376 /*
1377 * get_constraint_type
1378 * Return the pg_constraint.contype value for the given constraint.
1379 *
1380 * No frills.
1381 */
1382 char
1383 get_constraint_type(Oid conoid)
1384 {
1385 HeapTuple tp;
1386 char contype;
1387
1388 tp = SearchSysCache1(CONSTROID, ObjectIdGetDatum(conoid));
1389 if (!HeapTupleIsValid(tp))
1390 elog(ERROR, "cache lookup failed for constraint %u", conoid);
1391
1392 contype = ((Form_pg_constraint) GETSTRUCT(tp))->contype;
1393 ReleaseSysCache(tp);
1394
1395 return contype;
1396 }
1397
1398 /* ---------- LANGUAGE CACHE ---------- */
1399
1400 char *
1401 get_language_name(Oid langoid, bool missing_ok)
1402 {
1403 HeapTuple tp;
1404
1405 tp = SearchSysCache1(LANGOID, ObjectIdGetDatum(langoid));
1406 if (HeapTupleIsValid(tp))
1407 {
1408 Form_pg_language lantup = (Form_pg_language) GETSTRUCT(tp);
1409 char *result;
1410
1411 result = pstrdup(NameStr(lantup->lanname));
1412 ReleaseSysCache(tp);
1413 return result;
1414 }
1415
1416 if (!missing_ok)
1417 elog(ERROR, "cache lookup failed for language %u",
1418 langoid);
1419 return NULL;
1420 }
1421
1422 /* ---------- OPCLASS CACHE ---------- */
1423
1424 /*
1425 * get_opclass_family
1426 *
1427 * Returns the OID of the operator family the opclass belongs to.
1428 */
1429 Oid
1430 get_opclass_family(Oid opclass)
1431 {
1432 HeapTuple tp;
1433 Form_pg_opclass cla_tup;
1434 Oid result;
1435
1436 tp = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1437 if (!HeapTupleIsValid(tp))
1438 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1439 cla_tup = (Form_pg_opclass) GETSTRUCT(tp);
1440
1441 result = cla_tup->opcfamily;
1442 ReleaseSysCache(tp);
1443 return result;
1444 }
1445
1446 /*
1447 * get_opclass_input_type
1448 *
1449 * Returns the OID of the datatype the opclass indexes.
1450 */
1451 Oid
1452 get_opclass_input_type(Oid opclass)
1453 {
1454 HeapTuple tp;
1455 Form_pg_opclass cla_tup;
1456 Oid result;
1457
1458 tp = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1459 if (!HeapTupleIsValid(tp))
1460 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1461 cla_tup = (Form_pg_opclass) GETSTRUCT(tp);
1462
1463 result = cla_tup->opcintype;
1464 ReleaseSysCache(tp);
1465 return result;
1466 }
1467
1468 /*
1469 * get_opclass_opfamily_and_input_type
1470 *
1471 * Returns the OID of the operator family the opclass belongs to,
1472 * the OID of the datatype the opclass indexes
1473 */
1474 bool
1475 get_opclass_opfamily_and_input_type(Oid opclass, Oid *opfamily, Oid *opcintype)
1476 {
1477 HeapTuple tp;
1478 Form_pg_opclass cla_tup;
1479
1480 tp = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1481 if (!HeapTupleIsValid(tp))
1482 return false;
1483
1484 cla_tup = (Form_pg_opclass) GETSTRUCT(tp);
1485
1486 *opfamily = cla_tup->opcfamily;
1487 *opcintype = cla_tup->opcintype;
1488
1489 ReleaseSysCache(tp);
1490
1491 return true;
1492 }
1493
1494 /*
1495 * get_opclass_method
1496 *
1497 * Returns the OID of the index access method the opclass belongs to.
1498 */
1499 Oid
1500 get_opclass_method(Oid opclass)
1501 {
1502 HeapTuple tp;
1503 Form_pg_opclass cla_tup;
1504 Oid result;
1505
1506 tp = SearchSysCache1(CLAOID, ObjectIdGetDatum(opclass));
1507 if (!HeapTupleIsValid(tp))
1508 elog(ERROR, "cache lookup failed for opclass %u", opclass);
1509 cla_tup = (Form_pg_opclass) GETSTRUCT(tp);
1510
1511 result = cla_tup->opcmethod;
1512 ReleaseSysCache(tp);
1513 return result;
1514 }
1515
1516 /* ---------- OPFAMILY CACHE ---------- */
1517
1518 /*
1519 * get_opfamily_method
1520 *
1521 * Returns the OID of the index access method the opfamily is for.
1522 */
1523 Oid
1524 get_opfamily_method(Oid opfid)
1525 {
1526 HeapTuple tp;
1527 Form_pg_opfamily opfform;
1528 Oid result;
1529
1530 tp = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1531 if (!HeapTupleIsValid(tp))
1532 elog(ERROR, "cache lookup failed for operator family %u", opfid);
1533 opfform = (Form_pg_opfamily) GETSTRUCT(tp);
1534
1535 result = opfform->opfmethod;
1536 ReleaseSysCache(tp);
1537 return result;
1538 }
1539
1540 char *
1541 get_opfamily_name(Oid opfid, bool missing_ok)
1542 {
1543 HeapTuple tup;
1544 char *opfname;
1545 Form_pg_opfamily opfform;
1546
1547 tup = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opfid));
1548
1549 if (!HeapTupleIsValid(tup))
1550 {
1551 if (!missing_ok)
1552 elog(ERROR, "cache lookup failed for operator family %u", opfid);
1553 return NULL;
1554 }
1555
1556 opfform = (Form_pg_opfamily) GETSTRUCT(tup);
1557 opfname = pstrdup(NameStr(opfform->opfname));
1558
1559 ReleaseSysCache(tup);
1560
1561 return opfname;
1562 }
1563
1564 /* ---------- OPERATOR CACHE ---------- */
1565
1566 /*
1567 * get_opcode
1568 *
1569 * Returns the regproc id of the routine used to implement an
1570 * operator given the operator oid.
1571 */
1572 RegProcedure
1573 get_opcode(Oid opno)
1574 {
1575 HeapTuple tp;
1576
1577 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1578 if (HeapTupleIsValid(tp))
1579 {
1580 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1581 RegProcedure result;
1582
1583 result = optup->oprcode;
1584 ReleaseSysCache(tp);
1585 return result;
1586 }
1587 else
1588 return (RegProcedure) InvalidOid;
1589 }
1590
1591 /*
1592 * get_opname
1593 * returns the name of the operator with the given opno
1594 *
1595 * Note: returns a palloc'd copy of the string, or NULL if no such operator.
1596 */
1597 char *
1598 get_opname(Oid opno)
1599 {
1600 HeapTuple tp;
1601
1602 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1603 if (HeapTupleIsValid(tp))
1604 {
1605 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1606 char *result;
1607
1608 result = pstrdup(NameStr(optup->oprname));
1609 ReleaseSysCache(tp);
1610 return result;
1611 }
1612 else
1613 return NULL;
1614 }
1615
1616 /*
1617 * get_op_rettype
1618 * Given operator oid, return the operator's result type.
1619 */
1620 Oid
1621 get_op_rettype(Oid opno)
1622 {
1623 HeapTuple tp;
1624
1625 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1626 if (HeapTupleIsValid(tp))
1627 {
1628 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1629 Oid result;
1630
1631 result = optup->oprresult;
1632 ReleaseSysCache(tp);
1633 return result;
1634 }
1635 else
1636 return InvalidOid;
1637 }
1638
1639 /*
1640 * op_input_types
1641 *
1642 * Returns the left and right input datatypes for an operator
1643 * (InvalidOid if not relevant).
1644 */
1645 void
1646 op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
1647 {
1648 HeapTuple tp;
1649 Form_pg_operator optup;
1650
1651 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1652 if (!HeapTupleIsValid(tp)) /* shouldn't happen */
1653 elog(ERROR, "cache lookup failed for operator %u", opno);
1654 optup = (Form_pg_operator) GETSTRUCT(tp);
1655 *lefttype = optup->oprleft;
1656 *righttype = optup->oprright;
1657 ReleaseSysCache(tp);
1658 }
1659
1660 /*
1661 * op_mergejoinable
1662 *
1663 * Returns true if the operator is potentially mergejoinable. (The planner
1664 * will fail to find any mergejoin plans unless there are suitable btree
1665 * opfamily entries for this operator and associated sortops. The pg_operator
1666 * flag is just a hint to tell the planner whether to bother looking.)
1667 *
1668 * In some cases (currently only array_eq and record_eq), mergejoinability
1669 * depends on the specific input data type the operator is invoked for, so
1670 * that must be passed as well. We currently assume that only one input's type
1671 * is needed to check this --- by convention, pass the left input's data type.
1672 */
1673 bool
1674 op_mergejoinable(Oid opno, Oid inputtype)
1675 {
1676 bool result = false;
1677 HeapTuple tp;
1678 TypeCacheEntry *typentry;
1679
1680 /*
1681 * For array_eq or record_eq, we can sort if the element or field types
1682 * are all sortable. We could implement all the checks for that here, but
1683 * the typcache already does that and caches the results too, so let's
1684 * rely on the typcache. We do not need similar special cases for ranges
1685 * or multiranges, because their subtypes are required to be sortable.
1686 */
1687 if (opno == ARRAY_EQ_OP)
1688 {
1689 typentry = lookup_type_cache(inputtype, TYPECACHE_CMP_PROC);
1690 if (typentry->cmp_proc == F_BTARRAYCMP)
1691 result = true;
1692 }
1693 else if (opno == RECORD_EQ_OP)
1694 {
1695 typentry = lookup_type_cache(inputtype, TYPECACHE_CMP_PROC);
1696 if (typentry->cmp_proc == F_BTRECORDCMP)
1697 result = true;
1698 }
1699 else
1700 {
1701 /* For all other operators, rely on pg_operator.oprcanmerge */
1702 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1703 if (HeapTupleIsValid(tp))
1704 {
1705 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1706
1707 result = optup->oprcanmerge;
1708 ReleaseSysCache(tp);
1709 }
1710 }
1711 return result;
1712 }
1713
1714 /*
1715 * op_hashjoinable
1716 *
1717 * Returns true if the operator is hashjoinable. (There must be a suitable
1718 * hash opfamily entry for this operator if it is so marked.)
1719 *
1720 * In some cases (currently array_eq, record_eq, range_eq, multirange_eq),
1721 * hashjoinability depends on the specific input data type the operator is
1722 * invoked for, so that must be passed as well. We currently assume that only
1723 * one input's type is needed to check this --- by convention, pass the left
1724 * input's data type.
1725 */
1726 bool
1727 op_hashjoinable(Oid opno, Oid inputtype)
1728 {
1729 bool result = false;
1730 HeapTuple tp;
1731 TypeCacheEntry *typentry;
1732
1733 /* As in op_mergejoinable, let the typcache handle the hard cases */
1734 if (opno == ARRAY_EQ_OP)
1735 {
1736 typentry = lookup_type_cache(inputtype, TYPECACHE_HASH_PROC);
1737 if (typentry->hash_proc == F_HASH_ARRAY)
1738 result = true;
1739 }
1740 else if (opno == RECORD_EQ_OP)
1741 {
1742 typentry = lookup_type_cache(inputtype, TYPECACHE_HASH_PROC);
1743 if (typentry->hash_proc == F_HASH_RECORD)
1744 result = true;
1745 }
1746 else if (opno == RANGE_EQ_OP)
1747 {
1748 typentry = lookup_type_cache(inputtype, TYPECACHE_HASH_PROC);
1749 if (typentry->hash_proc == F_HASH_RANGE)
1750 result = true;
1751 }
1752 else if (opno == MULTIRANGE_EQ_OP)
1753 {
1754 typentry = lookup_type_cache(inputtype, TYPECACHE_HASH_PROC);
1755 if (typentry->hash_proc == F_HASH_MULTIRANGE)
1756 result = true;
1757 }
1758 else
1759 {
1760 /* For all other operators, rely on pg_operator.oprcanhash */
1761 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1762 if (HeapTupleIsValid(tp))
1763 {
1764 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1765
1766 result = optup->oprcanhash;
1767 ReleaseSysCache(tp);
1768 }
1769 }
1770 return result;
1771 }
1772
1773 /*
1774 * op_strict
1775 *
1776 * Get the proisstrict flag for the operator's underlying function.
1777 */
1778 bool
1779 op_strict(Oid opno)
1780 {
1781 RegProcedure funcid = get_opcode(opno);
1782
1783 if (funcid == (RegProcedure) InvalidOid)
1784 elog(ERROR, "operator %u does not exist", opno);
1785
1786 return func_strict((Oid) funcid);
1787 }
1788
1789 /*
1790 * op_volatile
1791 *
1792 * Get the provolatile flag for the operator's underlying function.
1793 */
1794 char
1795 op_volatile(Oid opno)
1796 {
1797 RegProcedure funcid = get_opcode(opno);
1798
1799 if (funcid == (RegProcedure) InvalidOid)
1800 elog(ERROR, "operator %u does not exist", opno);
1801
1802 return func_volatile((Oid) funcid);
1803 }
1804
1805 /*
1806 * get_commutator
1807 *
1808 * Returns the corresponding commutator of an operator.
1809 */
1810 Oid
1811 get_commutator(Oid opno)
1812 {
1813 HeapTuple tp;
1814
1815 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1816 if (HeapTupleIsValid(tp))
1817 {
1818 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1819 Oid result;
1820
1821 result = optup->oprcom;
1822 ReleaseSysCache(tp);
1823 return result;
1824 }
1825 else
1826 return InvalidOid;
1827 }
1828
1829 /*
1830 * get_negator
1831 *
1832 * Returns the corresponding negator of an operator.
1833 */
1834 Oid
1835 get_negator(Oid opno)
1836 {
1837 HeapTuple tp;
1838
1839 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1840 if (HeapTupleIsValid(tp))
1841 {
1842 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1843 Oid result;
1844
1845 result = optup->oprnegate;
1846 ReleaseSysCache(tp);
1847 return result;
1848 }
1849 else
1850 return InvalidOid;
1851 }
1852
1853 /*
1854 * get_oprrest
1855 *
1856 * Returns procedure id for computing selectivity of an operator.
1857 */
1858 RegProcedure
1859 get_oprrest(Oid opno)
1860 {
1861 HeapTuple tp;
1862
1863 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1864 if (HeapTupleIsValid(tp))
1865 {
1866 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1867 RegProcedure result;
1868
1869 result = optup->oprrest;
1870 ReleaseSysCache(tp);
1871 return result;
1872 }
1873 else
1874 return (RegProcedure) InvalidOid;
1875 }
1876
1877 /*
1878 * get_oprjoin
1879 *
1880 * Returns procedure id for computing selectivity of a join.
1881 */
1882 RegProcedure
1883 get_oprjoin(Oid opno)
1884 {
1885 HeapTuple tp;
1886
1887 tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno));
1888 if (HeapTupleIsValid(tp))
1889 {
1890 Form_pg_operator optup = (Form_pg_operator) GETSTRUCT(tp);
1891 RegProcedure result;
1892
1893 result = optup->oprjoin;
1894 ReleaseSysCache(tp);
1895 return result;
1896 }
1897 else
1898 return (RegProcedure) InvalidOid;
1899 }
1900
1901 /* ---------- FUNCTION CACHE ---------- */
1902
1903 /*
1904 * get_func_name
1905 * returns the name of the function with the given funcid
1906 *
1907 * Note: returns a palloc'd copy of the string, or NULL if no such function.
1908 */
1909 char *
1910 get_func_name(Oid funcid)
1911 {
1912 HeapTuple tp;
1913
1914 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1915 if (HeapTupleIsValid(tp))
1916 {
1917 Form_pg_proc functup = (Form_pg_proc) GETSTRUCT(tp);
1918 char *result;
1919
1920 result = pstrdup(NameStr(functup->proname));
1921 ReleaseSysCache(tp);
1922 return result;
1923 }
1924 else
1925 return NULL;
1926 }
1927
1928 /*
1929 * get_func_namespace
1930 *
1931 * Returns the pg_namespace OID associated with a given function.
1932 */
1933 Oid
1934 get_func_namespace(Oid funcid)
1935 {
1936 HeapTuple tp;
1937
1938 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1939 if (HeapTupleIsValid(tp))
1940 {
1941 Form_pg_proc functup = (Form_pg_proc) GETSTRUCT(tp);
1942 Oid result;
1943
1944 result = functup->pronamespace;
1945 ReleaseSysCache(tp);
1946 return result;
1947 }
1948 else
1949 return InvalidOid;
1950 }
1951
1952 /*
1953 * get_func_rettype
1954 * Given procedure id, return the function's result type.
1955 */
1956 Oid
1957 get_func_rettype(Oid funcid)
1958 {
1959 HeapTuple tp;
1960 Oid result;
1961
1962 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1963 if (!HeapTupleIsValid(tp))
1964 elog(ERROR, "cache lookup failed for function %u", funcid);
1965
1966 result = ((Form_pg_proc) GETSTRUCT(tp))->prorettype;
1967 ReleaseSysCache(tp);
1968 return result;
1969 }
1970
1971 /*
1972 * get_func_nargs
1973 * Given procedure id, return the number of arguments.
1974 */
1975 int
1976 get_func_nargs(Oid funcid)
1977 {
1978 HeapTuple tp;
1979 int result;
1980
1981 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
1982 if (!HeapTupleIsValid(tp))
1983 elog(ERROR, "cache lookup failed for function %u", funcid);
1984
1985 result = ((Form_pg_proc) GETSTRUCT(tp))->pronargs;
1986 ReleaseSysCache(tp);
1987 return result;
1988 }
1989
1990 /*
1991 * get_func_signature
1992 * Given procedure id, return the function's argument and result types.
1993 * (The return value is the result type.)
1994 *
1995 * The arguments are returned as a palloc'd array.
1996 */
1997 Oid
1998 get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
1999 {
2000 HeapTuple tp;
2001 Form_pg_proc procstruct;
2002 Oid result;
2003
2004 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2005 if (!HeapTupleIsValid(tp))
2006 elog(ERROR, "cache lookup failed for function %u", funcid);
2007
2008 procstruct = (Form_pg_proc) GETSTRUCT(tp);
2009
2010 result = procstruct->prorettype;
2011 *nargs = (int) procstruct->pronargs;
2012 Assert(*nargs == procstruct->proargtypes.dim1);
2013 *argtypes = (Oid *) palloc(*nargs * sizeof(Oid));
2014 memcpy(*argtypes, procstruct->proargtypes.values, *nargs * sizeof(Oid));
2015
2016 ReleaseSysCache(tp);
2017 return result;
2018 }
2019
2020 /*
2021 * get_func_variadictype
2022 * Given procedure id, return the function's provariadic field.
2023 */
2024 Oid
2025 get_func_variadictype(Oid funcid)
2026 {
2027 HeapTuple tp;
2028 Oid result;
2029
2030 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2031 if (!HeapTupleIsValid(tp))
2032 elog(ERROR, "cache lookup failed for function %u", funcid);
2033
2034 result = ((Form_pg_proc) GETSTRUCT(tp))->provariadic;
2035 ReleaseSysCache(tp);
2036 return result;
2037 }
2038
2039 /*
2040 * get_func_retset
2041 * Given procedure id, return the function's proretset flag.
2042 */
2043 bool
2044 get_func_retset(Oid funcid)
2045 {
2046 HeapTuple tp;
2047 bool result;
2048
2049 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2050 if (!HeapTupleIsValid(tp))
2051 elog(ERROR, "cache lookup failed for function %u", funcid);
2052
2053 result = ((Form_pg_proc) GETSTRUCT(tp))->proretset;
2054 ReleaseSysCache(tp);
2055 return result;
2056 }
2057
2058 /*
2059 * func_strict
2060 * Given procedure id, return the function's proisstrict flag.
2061 */
2062 bool
2063 func_strict(Oid funcid)
2064 {
2065 HeapTuple tp;
2066 bool result;
2067
2068 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2069 if (!HeapTupleIsValid(tp))
2070 elog(ERROR, "cache lookup failed for function %u", funcid);
2071
2072 result = ((Form_pg_proc) GETSTRUCT(tp))->proisstrict;
2073 ReleaseSysCache(tp);
2074 return result;
2075 }
2076
2077 /*
2078 * func_volatile
2079 * Given procedure id, return the function's provolatile flag.
2080 */
2081 char
2082 func_volatile(Oid funcid)
2083 {
2084 HeapTuple tp;
2085 char result;
2086
2087 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2088 if (!HeapTupleIsValid(tp))
2089 elog(ERROR, "cache lookup failed for function %u", funcid);
2090
2091 result = ((Form_pg_proc) GETSTRUCT(tp))->provolatile;
2092 ReleaseSysCache(tp);
2093 return result;
2094 }
2095
2096 /*
2097 * func_parallel
2098 * Given procedure id, return the function's proparallel flag.
2099 */
2100 char
2101 func_parallel(Oid funcid)
2102 {
2103 HeapTuple tp;
2104 char result;
2105
2106 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2107 if (!HeapTupleIsValid(tp))
2108 elog(ERROR, "cache lookup failed for function %u", funcid);
2109
2110 result = ((Form_pg_proc) GETSTRUCT(tp))->proparallel;
2111 ReleaseSysCache(tp);
2112 return result;
2113 }
2114
2115 /*
2116 * get_func_prokind
2117 * Given procedure id, return the routine kind.
2118 */
2119 char
2120 get_func_prokind(Oid funcid)
2121 {
2122 HeapTuple tp;
2123 char result;
2124
2125 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2126 if (!HeapTupleIsValid(tp))
2127 elog(ERROR, "cache lookup failed for function %u", funcid);
2128
2129 result = ((Form_pg_proc) GETSTRUCT(tp))->prokind;
2130 ReleaseSysCache(tp);
2131 return result;
2132 }
2133
2134 /*
2135 * get_func_leakproof
2136 * Given procedure id, return the function's leakproof field.
2137 */
2138 bool
2139 get_func_leakproof(Oid funcid)
2140 {
2141 HeapTuple tp;
2142 bool result;
2143
2144 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2145 if (!HeapTupleIsValid(tp))
2146 elog(ERROR, "cache lookup failed for function %u", funcid);
2147
2148 result = ((Form_pg_proc) GETSTRUCT(tp))->proleakproof;
2149 ReleaseSysCache(tp);
2150 return result;
2151 }
2152
2153 /*
2154 * get_func_support
2155 *
2156 * Returns the support function OID associated with a given function,
2157 * or InvalidOid if there is none.
2158 */
2159 RegProcedure
2160 get_func_support(Oid funcid)
2161 {
2162 HeapTuple tp;
2163
2164 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2165 if (HeapTupleIsValid(tp))
2166 {
2167 Form_pg_proc functup = (Form_pg_proc) GETSTRUCT(tp);
2168 RegProcedure result;
2169
2170 result = functup->prosupport;
2171 ReleaseSysCache(tp);
2172 return result;
2173 }
2174 else
2175 return (RegProcedure) InvalidOid;
2176 }
2177
2178 /* ---------- RELATION CACHE ---------- */
2179
2180 /*
2181 * get_relname_relid
2182 * Given name and namespace of a relation, look up the OID.
2183 *
2184 * Returns InvalidOid if there is no such relation.
2185 */
2186 Oid
2187 get_relname_relid(const char *relname, Oid relnamespace)
2188 {
2189 return GetSysCacheOid2(RELNAMENSP, Anum_pg_class_oid,
2190 PointerGetDatum(relname),
2191 ObjectIdGetDatum(relnamespace));
2192 }
2193
2194 #ifdef NOT_USED
2195 /*
2196 * get_relnatts
2197 *
2198 * Returns the number of attributes for a given relation.
2199 */
2200 int
2201 get_relnatts(Oid relid)
2202 {
2203 HeapTuple tp;
2204
2205 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2206 if (HeapTupleIsValid(tp))
2207 {
2208 Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
2209 int result;
2210
2211 result = reltup->relnatts;
2212 ReleaseSysCache(tp);
2213 return result;
2214 }
2215 else
2216 return InvalidAttrNumber;
2217 }
2218 #endif
2219
2220 /*
2221 * get_rel_name
2222 * Returns the name of a given relation.
2223 *
2224 * Returns a palloc'd copy of the string, or NULL if no such relation.
2225 *
2226 * NOTE: since relation name is not unique, be wary of code that uses this
2227 * for anything except preparing error messages.
2228 */
2229 char *
2230 get_rel_name(Oid relid)
2231 {
2232 HeapTuple tp;
2233
2234 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2235 if (HeapTupleIsValid(tp))
2236 {
2237 Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
2238 char *result;
2239
2240 result = pstrdup(NameStr(reltup->relname));
2241 ReleaseSysCache(tp);
2242 return result;
2243 }
2244 else
2245 return NULL;
2246 }
2247
2248 /*
2249 * get_rel_namespace
2250 *
2251 * Returns the pg_namespace OID associated with a given relation.
2252 */
2253 Oid
2254 get_rel_namespace(Oid relid)
2255 {
2256 HeapTuple tp;
2257
2258 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2259 if (HeapTupleIsValid(tp))
2260 {
2261 Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
2262 Oid result;
2263
2264 result = reltup->relnamespace;
2265 ReleaseSysCache(tp);
2266 return result;
2267 }
2268 else
2269 return InvalidOid;
2270 }
2271
2272 /*
2273 * get_rel_type_id
2274 *
2275 * Returns the pg_type OID associated with a given relation.
2276 *
2277 * Note: not all pg_class entries have associated pg_type OIDs; so be
2278 * careful to check for InvalidOid result.
2279 */
2280 Oid
2281 get_rel_type_id(Oid relid)
2282 {
2283 HeapTuple tp;
2284
2285 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2286 if (HeapTupleIsValid(tp))
2287 {
2288 Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
2289 Oid result;
2290
2291 result = reltup->reltype;
2292 ReleaseSysCache(tp);
2293 return result;
2294 }
2295 else
2296 return InvalidOid;
2297 }
2298
2299 /*
2300 * get_rel_relkind
2301 *
2302 * Returns the relkind associated with a given relation.
2303 */
2304 char
2305 get_rel_relkind(Oid relid)
2306 {
2307 HeapTuple tp;
2308
2309 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2310 if (HeapTupleIsValid(tp))
2311 {
2312 Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
2313 char result;
2314
2315 result = reltup->relkind;
2316 ReleaseSysCache(tp);
2317 return result;
2318 }
2319 else
2320 return '\0';
2321 }
2322
2323 /*
2324 * get_rel_relispartition
2325 *
2326 * Returns the relispartition flag associated with a given relation.
2327 */
2328 bool
2329 get_rel_relispartition(Oid relid)
2330 {
2331 HeapTuple tp;
2332
2333 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2334 if (HeapTupleIsValid(tp))
2335 {
2336 Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
2337 bool result;
2338
2339 result = reltup->relispartition;
2340 ReleaseSysCache(tp);
2341 return result;
2342 }
2343 else
2344 return false;
2345 }
2346
2347 /*
2348 * get_rel_tablespace
2349 *
2350 * Returns the pg_tablespace OID associated with a given relation.
2351 *
2352 * Note: InvalidOid might mean either that we couldn't find the relation,
2353 * or that it is in the database's default tablespace.
2354 */
2355 Oid
2356 get_rel_tablespace(Oid relid)
2357 {
2358 HeapTuple tp;
2359
2360 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2361 if (HeapTupleIsValid(tp))
2362 {
2363 Form_pg_class reltup = (Form_pg_class) GETSTRUCT(tp);
2364 Oid result;
2365
2366 result = reltup->reltablespace;
2367 ReleaseSysCache(tp);
2368 return result;
2369 }
2370 else
2371 return InvalidOid;
2372 }
2373
2374 /*
2375 * get_rel_persistence
2376 *
2377 * Returns the relpersistence associated with a given relation.
2378 */
2379 char
2380 get_rel_persistence(Oid relid)
2381 {
2382 HeapTuple tp;
2383 Form_pg_class reltup;
2384 char result;
2385
2386 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2387 if (!HeapTupleIsValid(tp))
2388 elog(ERROR, "cache lookup failed for relation %u", relid);
2389 reltup = (Form_pg_class) GETSTRUCT(tp);
2390 result = reltup->relpersistence;
2391 ReleaseSysCache(tp);
2392
2393 return result;
2394 }
2395
2396 /*
2397 * get_rel_relam
2398 *
2399 * Returns the relam associated with a given relation.
2400 */
2401 Oid
2402 get_rel_relam(Oid relid)
2403 {
2404 HeapTuple tp;
2405 Form_pg_class reltup;
2406 Oid result;
2407
2408 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2409 if (!HeapTupleIsValid(tp))
2410 elog(ERROR, "cache lookup failed for relation %u", relid);
2411 reltup = (Form_pg_class) GETSTRUCT(tp);
2412 result = reltup->relam;
2413 ReleaseSysCache(tp);
2414
2415 return result;
2416 }
2417
2418
2419 /* ---------- TRANSFORM CACHE ---------- */
2420
2421 Oid
2422 get_transform_fromsql(Oid typid, Oid langid, List *trftypes)
2423 {
2424 HeapTuple tup;
2425
2426 if (!list_member_oid(trftypes, typid))
2427 return InvalidOid;
2428
2429 tup = SearchSysCache2(TRFTYPELANG, ObjectIdGetDatum(typid),
2430 ObjectIdGetDatum(langid));
2431 if (HeapTupleIsValid(tup))
2432 {
2433 Oid funcid;
2434
2435 funcid = ((Form_pg_transform) GETSTRUCT(tup))->trffromsql;
2436 ReleaseSysCache(tup);
2437 return funcid;
2438 }
2439 else
2440 return InvalidOid;
2441 }
2442
2443 Oid
2444 get_transform_tosql(Oid typid, Oid langid, List *trftypes)
2445 {
2446 HeapTuple tup;
2447
2448 if (!list_member_oid(trftypes, typid))
2449 return InvalidOid;
2450
2451 tup = SearchSysCache2(TRFTYPELANG, ObjectIdGetDatum(typid),
2452 ObjectIdGetDatum(langid));
2453 if (HeapTupleIsValid(tup))
2454 {
2455 Oid funcid;
2456
2457 funcid = ((Form_pg_transform) GETSTRUCT(tup))->trftosql;
2458 ReleaseSysCache(tup);
2459 return funcid;
2460 }
2461 else
2462 return InvalidOid;
2463 }
2464
2465
2466 /* ---------- TYPE CACHE ---------- */
2467
2468 /*
2469 * get_typisdefined
2470 *
2471 * Given the type OID, determine whether the type is defined
2472 * (if not, it's only a shell).
2473 */
2474 bool
2475 get_typisdefined(Oid typid)
2476 {
2477 HeapTuple tp;
2478
2479 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2480 if (HeapTupleIsValid(tp))
2481 {
2482 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
2483 bool result;
2484
2485 result = typtup->typisdefined;
2486 ReleaseSysCache(tp);
2487 return result;
2488 }
2489 else
2490 return false;
2491 }
2492
2493 /*
2494 * get_typlen
2495 *
2496 * Given the type OID, return the length of the type.
2497 */
2498 int16
2499 get_typlen(Oid typid)
2500 {
2501 HeapTuple tp;
2502
2503 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2504 if (HeapTupleIsValid(tp))
2505 {
2506 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
2507 int16 result;
2508
2509 result = typtup->typlen;
2510 ReleaseSysCache(tp);
2511 return result;
2512 }
2513 else
2514 return 0;
2515 }
2516
2517 /*
2518 * get_typbyval
2519 *
2520 * Given the type OID, determine whether the type is returned by value or
2521 * not. Returns true if by value, false if by reference.
2522 */
2523 bool
2524 get_typbyval(Oid typid)
2525 {
2526 HeapTuple tp;
2527
2528 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2529 if (HeapTupleIsValid(tp))
2530 {
2531 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
2532 bool result;
2533
2534 result = typtup->typbyval;
2535 ReleaseSysCache(tp);
2536 return result;
2537 }
2538 else
2539 return false;
2540 }
2541
2542 /*
2543 * get_typlenbyval
2544 *
2545 * A two-fer: given the type OID, return both typlen and typbyval.
2546 *
2547 * Since both pieces of info are needed to know how to copy a Datum,
2548 * many places need both. Might as well get them with one cache lookup
2549 * instead of two. Also, this routine raises an error instead of
2550 * returning a bogus value when given a bad type OID.
2551 */
2552 void
2553 get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
2554 {
2555 HeapTuple tp;
2556 Form_pg_type typtup;
2557
2558 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2559 if (!HeapTupleIsValid(tp))
2560 elog(ERROR, "cache lookup failed for type %u", typid);
2561 typtup = (Form_pg_type) GETSTRUCT(tp);
2562 *typlen = typtup->typlen;
2563 *typbyval = typtup->typbyval;
2564 ReleaseSysCache(tp);
2565 }
2566
2567 /*
2568 * get_typlenbyvalalign
2569 *
2570 * A three-fer: given the type OID, return typlen, typbyval, typalign.
2571 */
2572 void
2573 get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval,
2574 char *typalign)
2575 {
2576 HeapTuple tp;
2577 Form_pg_type typtup;
2578
2579 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2580 if (!HeapTupleIsValid(tp))
2581 elog(ERROR, "cache lookup failed for type %u", typid);
2582 typtup = (Form_pg_type) GETSTRUCT(tp);
2583 *typlen = typtup->typlen;
2584 *typbyval = typtup->typbyval;
2585 *typalign = typtup->typalign;
2586 ReleaseSysCache(tp);
2587 }
2588
2589 /*
2590 * getTypeIOParam
2591 * Given a pg_type row, select the type OID to pass to I/O functions
2592 *
2593 * Formerly, all I/O functions were passed pg_type.typelem as their second
2594 * parameter, but we now have a more complex rule about what to pass.
2595 * This knowledge is intended to be centralized here --- direct references
2596 * to typelem elsewhere in the code are wrong, if they are associated with
2597 * I/O calls and not with actual subscripting operations! (But see
2598 * bootstrap.c's boot_get_type_io_data() if you need to change this.)
2599 *
2600 * As of PostgreSQL 8.1, output functions receive only the value itself
2601 * and not any auxiliary parameters, so the name of this routine is now
2602 * a bit of a misnomer ... it should be getTypeInputParam.
2603 */
2604 Oid
2605 getTypeIOParam(HeapTuple typeTuple)
2606 {
2607 Form_pg_type typeStruct = (Form_pg_type) GETSTRUCT(typeTuple);
2608
2609 /*
2610 * Array types get their typelem as parameter; everybody else gets their
2611 * own type OID as parameter.
2612 */
2613 if (OidIsValid(typeStruct->typelem))
2614 return typeStruct->typelem;
2615 else
2616 return typeStruct->oid;
2617 }
2618
2619 /*
2620 * get_type_io_data
2621 *
2622 * A six-fer: given the type OID, return typlen, typbyval, typalign,
2623 * typdelim, typioparam, and IO function OID. The IO function
2624 * returned is controlled by IOFuncSelector
2625 */
2626 void
2627 get_type_io_data(Oid typid,
2628 IOFuncSelector which_func,
2629 int16 *typlen,
2630 bool *typbyval,
2631 char *typalign,
2632 char *typdelim,
2633 Oid *typioparam,
2634 Oid *func)
2635 {
2636 HeapTuple typeTuple;
2637 Form_pg_type typeStruct;
2638
2639 /*
2640 * In bootstrap mode, pass it off to bootstrap.c. This hack allows us to
2641 * use array_in and array_out during bootstrap.
2642 */
2643 if (IsBootstrapProcessingMode())
2644 {
2645 Oid typinput;
2646 Oid typoutput;
2647
2648 boot_get_type_io_data(typid,
2649 typlen,
2650 typbyval,
2651 typalign,
2652 typdelim,
2653 typioparam,
2654 &typinput,
2655 &typoutput);
2656 switch (which_func)
2657 {
2658 case IOFunc_input:
2659 *func = typinput;
2660 break;
2661 case IOFunc_output:
2662 *func = typoutput;
2663 break;
2664 default:
2665 elog(ERROR, "binary I/O not supported during bootstrap");
2666 break;
2667 }
2668 return;
2669 }
2670
2671 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2672 if (!HeapTupleIsValid(typeTuple))
2673 elog(ERROR, "cache lookup failed for type %u", typid);
2674 typeStruct = (Form_pg_type) GETSTRUCT(typeTuple);
2675
2676 *typlen = typeStruct->typlen;
2677 *typbyval = typeStruct->typbyval;
2678 *typalign = typeStruct->typalign;
2679 *typdelim = typeStruct->typdelim;
2680 *typioparam = getTypeIOParam(typeTuple);
2681 switch (which_func)
2682 {
2683 case IOFunc_input:
2684 *func = typeStruct->typinput;
2685 break;
2686 case IOFunc_output:
2687 *func = typeStruct->typoutput;
2688 break;
2689 case IOFunc_receive:
2690 *func = typeStruct->typreceive;
2691 break;
2692 case IOFunc_send:
2693 *func = typeStruct->typsend;
2694 break;
2695 }
2696 ReleaseSysCache(typeTuple);
2697 }
2698
2699 #ifdef NOT_USED
2700 char
2701 get_typalign(Oid typid)
2702 {
2703 HeapTuple tp;
2704
2705 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2706 if (HeapTupleIsValid(tp))
2707 {
2708 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
2709 char result;
2710
2711 result = typtup->typalign;
2712 ReleaseSysCache(tp);
2713 return result;
2714 }
2715 else
2716 return TYPALIGN_INT;
2717 }
2718 #endif
2719
2720 char
2721 get_typstorage(Oid typid)
2722 {
2723 HeapTuple tp;
2724
2725 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2726 if (HeapTupleIsValid(tp))
2727 {
2728 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
2729 char result;
2730
2731 result = typtup->typstorage;
2732 ReleaseSysCache(tp);
2733 return result;
2734 }
2735 else
2736 return TYPSTORAGE_PLAIN;
2737 }
2738
2739 /*
2740 * get_typdefault
2741 * Given a type OID, return the type's default value, if any.
2742 *
2743 * The result is a palloc'd expression node tree, or NULL if there
2744 * is no defined default for the datatype.
2745 *
2746 * NB: caller should be prepared to coerce result to correct datatype;
2747 * the returned expression tree might produce something of the wrong type.
2748 */
2749 Node *
2750 get_typdefault(Oid typid)
2751 {
2752 HeapTuple typeTuple;
2753 Form_pg_type type;
2754 Datum datum;
2755 bool isNull;
2756 Node *expr;
2757
2758 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2759 if (!HeapTupleIsValid(typeTuple))
2760 elog(ERROR, "cache lookup failed for type %u", typid);
2761 type = (Form_pg_type) GETSTRUCT(typeTuple);
2762
2763 /*
2764 * typdefault and typdefaultbin are potentially null, so don't try to
2765 * access 'em as struct fields. Must do it the hard way with
2766 * SysCacheGetAttr.
2767 */
2768 datum = SysCacheGetAttr(TYPEOID,
2769 typeTuple,
2770 Anum_pg_type_typdefaultbin,
2771 &isNull);
2772
2773 if (!isNull)
2774 {
2775 /* We have an expression default */
2776 expr = stringToNode(TextDatumGetCString(datum));
2777 }
2778 else
2779 {
2780 /* Perhaps we have a plain literal default */
2781 datum = SysCacheGetAttr(TYPEOID,
2782 typeTuple,
2783 Anum_pg_type_typdefault,
2784 &isNull);
2785
2786 if (!isNull)
2787 {
2788 char *strDefaultVal;
2789
2790 /* Convert text datum to C string */
2791 strDefaultVal = TextDatumGetCString(datum);
2792 /* Convert C string to a value of the given type */
2793 datum = OidInputFunctionCall(type->typinput, strDefaultVal,
2794 getTypeIOParam(typeTuple), -1);
2795 /* Build a Const node containing the value */
2796 expr = (Node *) makeConst(typid,
2797 -1,
2798 type->typcollation,
2799 type->typlen,
2800 datum,
2801 false,
2802 type->typbyval);
2803 pfree(strDefaultVal);
2804 }
2805 else
2806 {
2807 /* No default */
2808 expr = NULL;
2809 }
2810 }
2811
2812 ReleaseSysCache(typeTuple);
2813
2814 return expr;
2815 }
2816
2817 /*
2818 * getBaseType
2819 * If the given type is a domain, return its base type;
2820 * otherwise return the type's own OID.
2821 */
2822 Oid
2823 getBaseType(Oid typid)
2824 {
2825 int32 typmod = -1;
2826
2827 return getBaseTypeAndTypmod(typid, &typmod);
2828 }
2829
2830 /*
2831 * getBaseTypeAndTypmod
2832 * If the given type is a domain, return its base type and typmod;
2833 * otherwise return the type's own OID, and leave *typmod unchanged.
2834 *
2835 * Note that the "applied typmod" should be -1 for every domain level
2836 * above the bottommost; therefore, if the passed-in typid is indeed
2837 * a domain, *typmod should be -1.
2838 */
2839 Oid
2840 getBaseTypeAndTypmod(Oid typid, int32 *typmod)
2841 {
2842 /*
2843 * We loop to find the bottom base type in a stack of domains.
2844 */
2845 for (;;)
2846 {
2847 HeapTuple tup;
2848 Form_pg_type typTup;
2849
2850 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2851 if (!HeapTupleIsValid(tup))
2852 elog(ERROR, "cache lookup failed for type %u", typid);
2853 typTup = (Form_pg_type) GETSTRUCT(tup);
2854 if (typTup->typtype != TYPTYPE_DOMAIN)
2855 {
2856 /* Not a domain, so done */
2857 ReleaseSysCache(tup);
2858 break;
2859 }
2860
2861 Assert(*typmod == -1);
2862 typid = typTup->typbasetype;
2863 *typmod = typTup->typtypmod;
2864
2865 ReleaseSysCache(tup);
2866 }
2867
2868 return typid;
2869 }
2870
2871 /*
2872 * get_typavgwidth
2873 *
2874 * Given a type OID and a typmod value (pass -1 if typmod is unknown),
2875 * estimate the average width of values of the type. This is used by
2876 * the planner, which doesn't require absolutely correct results;
2877 * it's OK (and expected) to guess if we don't know for sure.
2878 */
2879 int32
2880 get_typavgwidth(Oid typid, int32 typmod)
2881 {
2882 int typlen = get_typlen(typid);
2883 int32 maxwidth;
2884
2885 /*
2886 * Easy if it's a fixed-width type
2887 */
2888 if (typlen > 0)
2889 return typlen;
2890
2891 /*
2892 * type_maximum_size knows the encoding of typmod for some datatypes;
2893 * don't duplicate that knowledge here.
2894 */
2895 maxwidth = type_maximum_size(typid, typmod);
2896 if (maxwidth > 0)
2897 {
2898 /*
2899 * For BPCHAR, the max width is also the only width. Otherwise we
2900 * need to guess about the typical data width given the max. A sliding
2901 * scale for percentage of max width seems reasonable.
2902 */
2903 if (typid == BPCHAROID)
2904 return maxwidth;
2905 if (maxwidth <= 32)
2906 return maxwidth; /* assume full width */
2907 if (maxwidth < 1000)
2908 return 32 + (maxwidth - 32) / 2; /* assume 50% */
2909
2910 /*
2911 * Beyond 1000, assume we're looking at something like
2912 * "varchar(10000)" where the limit isn't actually reached often, and
2913 * use a fixed estimate.
2914 */
2915 return 32 + (1000 - 32) / 2;
2916 }
2917
2918 /*
2919 * Oops, we have no idea ... wild guess time.
2920 */
2921 return 32;
2922 }
2923
2924 /*
2925 * get_typtype
2926 *
2927 * Given the type OID, find if it is a basic type, a complex type, etc.
2928 * It returns the null char if the cache lookup fails...
2929 */
2930 char
2931 get_typtype(Oid typid)
2932 {
2933 HeapTuple tp;
2934
2935 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
2936 if (HeapTupleIsValid(tp))
2937 {
2938 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
2939 char result;
2940
2941 result = typtup->typtype;
2942 ReleaseSysCache(tp);
2943 return result;
2944 }
2945 else
2946 return '\0';
2947 }
2948
2949 /*
2950 * type_is_rowtype
2951 *
2952 * Convenience function to determine whether a type OID represents
2953 * a "rowtype" type --- either RECORD or a named composite type
2954 * (including a domain over a named composite type).
2955 */
2956 bool
2957 type_is_rowtype(Oid typid)
2958 {
2959 if (typid == RECORDOID)
2960 return true; /* easy case */
2961 switch (get_typtype(typid))
2962 {
2963 case TYPTYPE_COMPOSITE:
2964 return true;
2965 case TYPTYPE_DOMAIN:
2966 if (get_typtype(getBaseType(typid)) == TYPTYPE_COMPOSITE)
2967 return true;
2968 break;
2969 default:
2970 break;
2971 }
2972 return false;
2973 }
2974
2975 /*
2976 * type_is_enum
2977 * Returns true if the given type is an enum type.
2978 */
2979 bool
2980 type_is_enum(Oid typid)
2981 {
2982 return (get_typtype(typid) == TYPTYPE_ENUM);
2983 }
2984
2985 /*
2986 * type_is_range
2987 * Returns true if the given type is a range type.
2988 */
2989 bool
2990 type_is_range(Oid typid)
2991 {
2992 return (get_typtype(typid) == TYPTYPE_RANGE);
2993 }
2994
2995 /*
2996 * type_is_multirange
2997 * Returns true if the given type is a multirange type.
2998 */
2999 bool
3000 type_is_multirange(Oid typid)
3001 {
3002 return (get_typtype(typid) == TYPTYPE_MULTIRANGE);
3003 }
3004
3005 /*
3006 * get_type_category_preferred
3007 *
3008 * Given the type OID, fetch its category and preferred-type status.
3009 * Throws error on failure.
3010 */
3011 void
3012 get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
3013 {
3014 HeapTuple tp;
3015 Form_pg_type typtup;
3016
3017 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3018 if (!HeapTupleIsValid(tp))
3019 elog(ERROR, "cache lookup failed for type %u", typid);
3020 typtup = (Form_pg_type) GETSTRUCT(tp);
3021 *typcategory = typtup->typcategory;
3022 *typispreferred = typtup->typispreferred;
3023 ReleaseSysCache(tp);
3024 }
3025
3026 /*
3027 * get_typ_typrelid
3028 *
3029 * Given the type OID, get the typrelid (InvalidOid if not a complex
3030 * type).
3031 */
3032 Oid
3033 get_typ_typrelid(Oid typid)
3034 {
3035 HeapTuple tp;
3036
3037 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3038 if (HeapTupleIsValid(tp))
3039 {
3040 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
3041 Oid result;
3042
3043 result = typtup->typrelid;
3044 ReleaseSysCache(tp);
3045 return result;
3046 }
3047 else
3048 return InvalidOid;
3049 }
3050
3051 /*
3052 * get_element_type
3053 *
3054 * Given the type OID, get the typelem (InvalidOid if not an array type).
3055 *
3056 * NB: this only succeeds for "true" arrays having array_subscript_handler
3057 * as typsubscript. For other types, InvalidOid is returned independently
3058 * of whether they have typelem or typsubscript set.
3059 */
3060 Oid
3061 get_element_type(Oid typid)
3062 {
3063 HeapTuple tp;
3064
3065 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3066 if (HeapTupleIsValid(tp))
3067 {
3068 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
3069 Oid result;
3070
3071 if (IsTrueArrayType(typtup))
3072 result = typtup->typelem;
3073 else
3074 result = InvalidOid;
3075 ReleaseSysCache(tp);
3076 return result;
3077 }
3078 else
3079 return InvalidOid;
3080 }
3081
3082 /*
3083 * get_array_type
3084 *
3085 * Given the type OID, get the corresponding "true" array type.
3086 * Returns InvalidOid if no array type can be found.
3087 */
3088 Oid
3089 get_array_type(Oid typid)
3090 {
3091 HeapTuple tp;
3092 Oid result = InvalidOid;
3093
3094 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3095 if (HeapTupleIsValid(tp))
3096 {
3097 result = ((Form_pg_type) GETSTRUCT(tp))->typarray;
3098 ReleaseSysCache(tp);
3099 }
3100 return result;
3101 }
3102
3103 /*
3104 * get_promoted_array_type
3105 *
3106 * The "promoted" type is what you'd get from an ARRAY(SELECT ...)
3107 * construct, that is, either the corresponding "true" array type
3108 * if the input is a scalar type that has such an array type,
3109 * or the same type if the input is already a "true" array type.
3110 * Returns InvalidOid if neither rule is satisfied.
3111 */
3112 Oid
3113 get_promoted_array_type(Oid typid)
3114 {
3115 Oid array_type = get_array_type(typid);
3116
3117 if (OidIsValid(array_type))
3118 return array_type;
3119 if (OidIsValid(get_element_type(typid)))
3120 return typid;
3121 return InvalidOid;
3122 }
3123
3124 /*
3125 * get_base_element_type
3126 * Given the type OID, get the typelem, looking "through" any domain
3127 * to its underlying array type.
3128 *
3129 * This is equivalent to get_element_type(getBaseType(typid)), but avoids
3130 * an extra cache lookup. Note that it fails to provide any information
3131 * about the typmod of the array.
3132 */
3133 Oid
3134 get_base_element_type(Oid typid)
3135 {
3136 /*
3137 * We loop to find the bottom base type in a stack of domains.
3138 */
3139 for (;;)
3140 {
3141 HeapTuple tup;
3142 Form_pg_type typTup;
3143
3144 tup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3145 if (!HeapTupleIsValid(tup))
3146 break;
3147 typTup = (Form_pg_type) GETSTRUCT(tup);
3148 if (typTup->typtype != TYPTYPE_DOMAIN)
3149 {
3150 /* Not a domain, so stop descending */
3151 Oid result;
3152
3153 /* This test must match get_element_type */
3154 if (IsTrueArrayType(typTup))
3155 result = typTup->typelem;
3156 else
3157 result = InvalidOid;
3158 ReleaseSysCache(tup);
3159 return result;
3160 }
3161
3162 typid = typTup->typbasetype;
3163 ReleaseSysCache(tup);
3164 }
3165
3166 /* Like get_element_type, silently return InvalidOid for bogus input */
3167 return InvalidOid;
3168 }
3169
3170 /*
3171 * getTypeInputInfo
3172 *
3173 * Get info needed for converting values of a type to internal form
3174 */
3175 void
3176 getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
3177 {
3178 HeapTuple typeTuple;
3179 Form_pg_type pt;
3180
3181 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type));
3182 if (!HeapTupleIsValid(typeTuple))
3183 elog(ERROR, "cache lookup failed for type %u", type);
3184 pt = (Form_pg_type) GETSTRUCT(typeTuple);
3185
3186 if (!pt->typisdefined)
3187 ereport(ERROR,
3188 (errcode(ERRCODE_UNDEFINED_OBJECT),
3189 errmsg("type %s is only a shell",
3190 format_type_be(type))));
3191 if (!OidIsValid(pt->typinput))
3192 ereport(ERROR,
3193 (errcode(ERRCODE_UNDEFINED_FUNCTION),
3194 errmsg("no input function available for type %s",
3195 format_type_be(type))));
3196
3197 *typInput = pt->typinput;
3198 *typIOParam = getTypeIOParam(typeTuple);
3199
3200 ReleaseSysCache(typeTuple);
3201 }
3202
3203 /*
3204 * getTypeOutputInfo
3205 *
3206 * Get info needed for printing values of a type
3207 */
3208 void
3209 getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
3210 {
3211 HeapTuple typeTuple;
3212 Form_pg_type pt;
3213
3214 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type));
3215 if (!HeapTupleIsValid(typeTuple))
3216 elog(ERROR, "cache lookup failed for type %u", type);
3217 pt = (Form_pg_type) GETSTRUCT(typeTuple);
3218
3219 if (!pt->typisdefined)
3220 ereport(ERROR,
3221 (errcode(ERRCODE_UNDEFINED_OBJECT),
3222 errmsg("type %s is only a shell",
3223 format_type_be(type))));
3224 if (!OidIsValid(pt->typoutput))
3225 ereport(ERROR,
3226 (errcode(ERRCODE_UNDEFINED_FUNCTION),
3227 errmsg("no output function available for type %s",
3228 format_type_be(type))));
3229
3230 *typOutput = pt->typoutput;
3231 *typIsVarlena = (!pt->typbyval) && (pt->typlen == -1);
3232
3233 ReleaseSysCache(typeTuple);
3234 }
3235
3236 /*
3237 * getTypeBinaryInputInfo
3238 *
3239 * Get info needed for binary input of values of a type
3240 */
3241 void
3242 getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
3243 {
3244 HeapTuple typeTuple;
3245 Form_pg_type pt;
3246
3247 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type));
3248 if (!HeapTupleIsValid(typeTuple))
3249 elog(ERROR, "cache lookup failed for type %u", type);
3250 pt = (Form_pg_type) GETSTRUCT(typeTuple);
3251
3252 if (!pt->typisdefined)
3253 ereport(ERROR,
3254 (errcode(ERRCODE_UNDEFINED_OBJECT),
3255 errmsg("type %s is only a shell",
3256 format_type_be(type))));
3257 if (!OidIsValid(pt->typreceive))
3258 ereport(ERROR,
3259 (errcode(ERRCODE_UNDEFINED_FUNCTION),
3260 errmsg("no binary input function available for type %s",
3261 format_type_be(type))));
3262
3263 *typReceive = pt->typreceive;
3264 *typIOParam = getTypeIOParam(typeTuple);
3265
3266 ReleaseSysCache(typeTuple);
3267 }
3268
3269 /*
3270 * getTypeBinaryOutputInfo
3271 *
3272 * Get info needed for binary output of values of a type
3273 */
3274 void
3275 getTypeBinaryOutputInfo(Oid type, Oid *typSend, bool *typIsVarlena)
3276 {
3277 HeapTuple typeTuple;
3278 Form_pg_type pt;
3279
3280 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type));
3281 if (!HeapTupleIsValid(typeTuple))
3282 elog(ERROR, "cache lookup failed for type %u", type);
3283 pt = (Form_pg_type) GETSTRUCT(typeTuple);
3284
3285 if (!pt->typisdefined)
3286 ereport(ERROR,
3287 (errcode(ERRCODE_UNDEFINED_OBJECT),
3288 errmsg("type %s is only a shell",
3289 format_type_be(type))));
3290 if (!OidIsValid(pt->typsend))
3291 ereport(ERROR,
3292 (errcode(ERRCODE_UNDEFINED_FUNCTION),
3293 errmsg("no binary output function available for type %s",
3294 format_type_be(type))));
3295
3296 *typSend = pt->typsend;
3297 *typIsVarlena = (!pt->typbyval) && (pt->typlen == -1);
3298
3299 ReleaseSysCache(typeTuple);
3300 }
3301
3302 /*
3303 * get_typmodin
3304 *
3305 * Given the type OID, return the type's typmodin procedure, if any.
3306 */
3307 Oid
3308 get_typmodin(Oid typid)
3309 {
3310 HeapTuple tp;
3311
3312 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3313 if (HeapTupleIsValid(tp))
3314 {
3315 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
3316 Oid result;
3317
3318 result = typtup->typmodin;
3319 ReleaseSysCache(tp);
3320 return result;
3321 }
3322 else
3323 return InvalidOid;
3324 }
3325
3326 #ifdef NOT_USED
3327 /*
3328 * get_typmodout
3329 *
3330 * Given the type OID, return the type's typmodout procedure, if any.
3331 */
3332 Oid
3333 get_typmodout(Oid typid)
3334 {
3335 HeapTuple tp;
3336
3337 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3338 if (HeapTupleIsValid(tp))
3339 {
3340 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
3341 Oid result;
3342
3343 result = typtup->typmodout;
3344 ReleaseSysCache(tp);
3345 return result;
3346 }
3347 else
3348 return InvalidOid;
3349 }
3350 #endif /* NOT_USED */
3351
3352 /*
3353 * get_typcollation
3354 *
3355 * Given the type OID, return the type's typcollation attribute.
3356 */
3357 Oid
3358 get_typcollation(Oid typid)
3359 {
3360 HeapTuple tp;
3361
3362 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3363 if (HeapTupleIsValid(tp))
3364 {
3365 Form_pg_type typtup = (Form_pg_type) GETSTRUCT(tp);
3366 Oid result;
3367
3368 result = typtup->typcollation;
3369 ReleaseSysCache(tp);
3370 return result;
3371 }
3372 else
3373 return InvalidOid;
3374 }
3375
3376
3377 /*
3378 * type_is_collatable
3379 *
3380 * Return whether the type cares about collations
3381 */
3382 bool
3383 type_is_collatable(Oid typid)
3384 {
3385 return OidIsValid(get_typcollation(typid));
3386 }
3387
3388
3389 /*
3390 * get_typsubscript
3391 *
3392 * Given the type OID, return the type's subscripting handler's OID,
3393 * if it has one.
3394 *
3395 * If typelemp isn't NULL, we also store the type's typelem value there.
3396 * This saves some callers an extra catalog lookup.
3397 */
3398 RegProcedure
3399 get_typsubscript(Oid typid, Oid *typelemp)
3400 {
3401 HeapTuple tp;
3402
3403 tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
3404 if (HeapTupleIsValid(tp))
3405 {
3406 Form_pg_type typform = (Form_pg_type) GETSTRUCT(tp);
3407 RegProcedure handler = typform->typsubscript;
3408
3409 if (typelemp)
3410 *typelemp = typform->typelem;
3411 ReleaseSysCache(tp);
3412 return handler;
3413 }
3414 else
3415 {
3416 if (typelemp)
3417 *typelemp = InvalidOid;
3418 return InvalidOid;
3419 }
3420 }
3421
3422 /*
3423 * getSubscriptingRoutines
3424 *
3425 * Given the type OID, fetch the type's subscripting methods struct.
3426 * Return NULL if type is not subscriptable.
3427 *
3428 * If typelemp isn't NULL, we also store the type's typelem value there.
3429 * This saves some callers an extra catalog lookup.
3430 */
3431 const struct SubscriptRoutines *
3432 getSubscriptingRoutines(Oid typid, Oid *typelemp)
3433 {
3434 RegProcedure typsubscript = get_typsubscript(typid, typelemp);
3435
3436 if (!OidIsValid(typsubscript))
3437 return NULL;
3438
3439 return (const struct SubscriptRoutines *)
3440 DatumGetPointer(OidFunctionCall0(typsubscript));
3441 }
3442
3443
3444 /* ---------- STATISTICS CACHE ---------- */
3445
3446 /*
3447 * get_attavgwidth
3448 *
3449 * Given the table and attribute number of a column, get the average
3450 * width of entries in the column. Return zero if no data available.
3451 *
3452 * Currently this is only consulted for individual tables, not for inheritance
3453 * trees, so we don't need an "inh" parameter.
3454 *
3455 * Calling a hook at this point looks somewhat strange, but is required
3456 * because the optimizer calls this function without any other way for
3457 * plug-ins to control the result.
3458 */
3459 int32
3460 get_attavgwidth(Oid relid, AttrNumber attnum)
3461 {
3462 HeapTuple tp;
3463 int32 stawidth;
3464
3465 if (get_attavgwidth_hook)
3466 {
3467 stawidth = (*get_attavgwidth_hook) (relid, attnum);
3468 if (stawidth > 0)
3469 return stawidth;
3470 }
3471 tp = SearchSysCache3(STATRELATTINH,
3472 ObjectIdGetDatum(relid),
3473 Int16GetDatum(attnum),
3474 BoolGetDatum(false));
3475 if (HeapTupleIsValid(tp))
3476 {
3477 stawidth = ((Form_pg_statistic) GETSTRUCT(tp))->stawidth;
3478 ReleaseSysCache(tp);
3479 if (stawidth > 0)
3480 return stawidth;
3481 }
3482 return 0;
3483 }
3484
3485 /*
3486 * get_attstatsslot
3487 *
3488 * Extract the contents of a "slot" of a pg_statistic tuple.
3489 * Returns true if requested slot type was found, else false.
3490 *
3491 * Unlike other routines in this file, this takes a pointer to an
3492 * already-looked-up tuple in the pg_statistic cache. We do this since
3493 * most callers will want to extract more than one value from the cache
3494 * entry, and we don't want to repeat the cache lookup unnecessarily.
3495 * Also, this API allows this routine to be used with statistics tuples
3496 * that have been provided by a stats hook and didn't really come from
3497 * pg_statistic.
3498 *
3499 * sslot: pointer to output area (typically, a local variable in the caller).
3500 * statstuple: pg_statistic tuple to be examined.
3501 * reqkind: STAKIND code for desired statistics slot kind.
3502 * reqop: STAOP value wanted, or InvalidOid if don't care.
3503 * flags: bitmask of ATTSTATSSLOT_VALUES and/or ATTSTATSSLOT_NUMBERS.
3504 *
3505 * If a matching slot is found, true is returned, and *sslot is filled thus:
3506 * staop: receives the actual STAOP value.
3507 * stacoll: receives the actual STACOLL value.
3508 * valuetype: receives actual datatype of the elements of stavalues.
3509 * values: receives pointer to an array of the slot's stavalues.
3510 * nvalues: receives number of stavalues.
3511 * numbers: receives pointer to an array of the slot's stanumbers (as float4).
3512 * nnumbers: receives number of stanumbers.
3513 *
3514 * valuetype/values/nvalues are InvalidOid/NULL/0 if ATTSTATSSLOT_VALUES
3515 * wasn't specified. Likewise, numbers/nnumbers are NULL/0 if
3516 * ATTSTATSSLOT_NUMBERS wasn't specified.
3517 *
3518 * If no matching slot is found, false is returned, and *sslot is zeroed.
3519 *
3520 * Note that the current API doesn't allow for searching for a slot with
3521 * a particular collation. If we ever actually support recording more than
3522 * one collation, we'll have to extend the API, but for now simple is good.
3523 *
3524 * The data referred to by the fields of sslot is locally palloc'd and
3525 * is independent of the original pg_statistic tuple. When the caller
3526 * is done with it, call free_attstatsslot to release the palloc'd data.
3527 *
3528 * If it's desirable to call free_attstatsslot when get_attstatsslot might
3529 * not have been called, memset'ing sslot to zeroes will allow that.
3530 *
3531 * Passing flags=0 can be useful to quickly check if the requested slot type
3532 * exists. In this case no arrays are extracted, so free_attstatsslot need
3533 * not be called.
3534 */
3535 bool
3536 get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple,
3537 int reqkind, Oid reqop, int flags)
3538 {
3539 Form_pg_statistic stats = (Form_pg_statistic) GETSTRUCT(statstuple);
3540 int i;
3541 Datum val;
3542 ArrayType *statarray;
3543 Oid arrayelemtype;
3544 int narrayelem;
3545 HeapTuple typeTuple;
3546 Form_pg_type typeForm;
3547
3548 /* initialize *sslot properly */
3549 memset(sslot, 0, sizeof(AttStatsSlot));
3550
3551 for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
3552 {
3553 if ((&stats->stakind1)[i] == reqkind &&
3554 (reqop == InvalidOid || (&stats->staop1)[i] == reqop))
3555 break;
3556 }
3557 if (i >= STATISTIC_NUM_SLOTS)
3558 return false; /* not there */
3559
3560 sslot->staop = (&stats->staop1)[i];
3561 sslot->stacoll = (&stats->stacoll1)[i];
3562
3563 if (flags & ATTSTATSSLOT_VALUES)
3564 {
3565 val = SysCacheGetAttrNotNull(STATRELATTINH, statstuple,
3566 Anum_pg_statistic_stavalues1 + i);
3567
3568 /*
3569 * Detoast the array if needed, and in any case make a copy that's
3570 * under control of this AttStatsSlot.
3571 */
3572 statarray = DatumGetArrayTypePCopy(val);
3573
3574 /*
3575 * Extract the actual array element type, and pass it back in case the
3576 * caller needs it.
3577 */
3578 sslot->valuetype = arrayelemtype = ARR_ELEMTYPE(statarray);
3579
3580 /* Need info about element type */
3581 typeTuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(arrayelemtype));
3582 if (!HeapTupleIsValid(typeTuple))
3583 elog(ERROR, "cache lookup failed for type %u", arrayelemtype);
3584 typeForm = (Form_pg_type) GETSTRUCT(typeTuple);
3585
3586 /* Deconstruct array into Datum elements; NULLs not expected */
3587 deconstruct_array(statarray,
3588 arrayelemtype,
3589 typeForm->typlen,
3590 typeForm->typbyval,
3591 typeForm->typalign,
3592 &sslot->values, NULL, &sslot->nvalues);
3593
3594 /*
3595 * If the element type is pass-by-reference, we now have a bunch of
3596 * Datums that are pointers into the statarray, so we need to keep
3597 * that until free_attstatsslot. Otherwise, all the useful info is in
3598 * sslot->values[], so we can free the array object immediately.
3599 */
3600 if (!typeForm->typbyval)
3601 sslot->values_arr = statarray;
3602 else
3603 pfree(statarray);
3604
3605 ReleaseSysCache(typeTuple);
3606 }
3607
3608 if (flags & ATTSTATSSLOT_NUMBERS)
3609 {
3610 val = SysCacheGetAttrNotNull(STATRELATTINH, statstuple,
3611 Anum_pg_statistic_stanumbers1 + i);
3612
3613 /*
3614 * Detoast the array if needed, and in any case make a copy that's
3615 * under control of this AttStatsSlot.
3616 */
3617 statarray = DatumGetArrayTypePCopy(val);
3618
3619 /*
3620 * We expect the array to be a 1-D float4 array; verify that. We don't
3621 * need to use deconstruct_array() since the array data is just going
3622 * to look like a C array of float4 values.
3623 */
3624 narrayelem = ARR_DIMS(statarray)[0];
3625 if (ARR_NDIM(statarray) != 1 || narrayelem <= 0 ||
3626 ARR_HASNULL(statarray) ||
3627 ARR_ELEMTYPE(statarray) != FLOAT4OID)
3628 elog(ERROR, "stanumbers is not a 1-D float4 array");
3629
3630 /* Give caller a pointer directly into the statarray */
3631 sslot->numbers = (float4 *) ARR_DATA_PTR(statarray);
3632 sslot->nnumbers = narrayelem;
3633
3634 /* We'll free the statarray in free_attstatsslot */
3635 sslot->numbers_arr = statarray;
3636 }
3637
3638 return true;
3639 }
3640
3641 /*
3642 * free_attstatsslot
3643 * Free data allocated by get_attstatsslot
3644 */
3645 void
3646 free_attstatsslot(AttStatsSlot *sslot)
3647 {
3648 /* The values[] array was separately palloc'd by deconstruct_array */
3649 if (sslot->values)
3650 pfree(sslot->values);
3651 /* The numbers[] array points into numbers_arr, do not pfree it */
3652 /* Free the detoasted array objects, if any */
3653 if (sslot->values_arr)
3654 pfree(sslot->values_arr);
3655 if (sslot->numbers_arr)
3656 pfree(sslot->numbers_arr);
3657 }
3658
3659 /* ---------- PG_NAMESPACE CACHE ---------- */
3660
3661 /*
3662 * get_namespace_name
3663 * Returns the name of a given namespace
3664 *
3665 * Returns a palloc'd copy of the string, or NULL if no such namespace.
3666 */
3667 char *
3668 get_namespace_name(Oid nspid)
3669 {
3670 HeapTuple tp;
3671
3672 tp = SearchSysCache1(NAMESPACEOID, ObjectIdGetDatum(nspid));
3673 if (HeapTupleIsValid(tp))
3674 {
3675 Form_pg_namespace nsptup = (Form_pg_namespace) GETSTRUCT(tp);
3676 char *result;
3677
3678 result = pstrdup(NameStr(nsptup->nspname));
3679 ReleaseSysCache(tp);
3680 return result;
3681 }
3682 else
3683 return NULL;
3684 }
3685
3686 /*
3687 * get_namespace_name_or_temp
3688 * As above, but if it is this backend's temporary namespace, return
3689 * "pg_temp" instead.
3690 */
3691 char *
3692 get_namespace_name_or_temp(Oid nspid)
3693 {
3694 if (isTempNamespace(nspid))
3695 return pstrdup("pg_temp");
3696 else
3697 return get_namespace_name(nspid);
3698 }
3699
3700 /* ---------- PG_RANGE CACHES ---------- */
3701
3702 /*
3703 * get_range_subtype
3704 * Returns the subtype of a given range type
3705 *
3706 * Returns InvalidOid if the type is not a range type.
3707 */
3708 Oid
3709 get_range_subtype(Oid rangeOid)
3710 {
3711 HeapTuple tp;
3712
3713 tp = SearchSysCache1(RANGETYPE, ObjectIdGetDatum(rangeOid));
3714 if (HeapTupleIsValid(tp))
3715 {
3716 Form_pg_range rngtup = (Form_pg_range) GETSTRUCT(tp);
3717 Oid result;
3718
3719 result = rngtup->rngsubtype;
3720 ReleaseSysCache(tp);
3721 return result;
3722 }
3723 else
3724 return InvalidOid;
3725 }
3726
3727 /*
3728 * get_range_collation
3729 * Returns the collation of a given range type
3730 *
3731 * Returns InvalidOid if the type is not a range type,
3732 * or if its subtype is not collatable.
3733 */
3734 Oid
3735 get_range_collation(Oid rangeOid)
3736 {
3737 HeapTuple tp;
3738
3739 tp = SearchSysCache1(RANGETYPE, ObjectIdGetDatum(rangeOid));
3740 if (HeapTupleIsValid(tp))
3741 {
3742 Form_pg_range rngtup = (Form_pg_range) GETSTRUCT(tp);
3743 Oid result;
3744
3745 result = rngtup->rngcollation;
3746 ReleaseSysCache(tp);
3747 return result;
3748 }
3749 else
3750 return InvalidOid;
3751 }
3752
3753 /*
3754 * get_range_multirange
3755 * Returns the multirange type of a given range type
3756 *
3757 * Returns InvalidOid if the type is not a range type.
3758 */
3759 Oid
3760 get_range_multirange(Oid rangeOid)
3761 {
3762 HeapTuple tp;
3763
3764 tp = SearchSysCache1(RANGETYPE, ObjectIdGetDatum(rangeOid));
3765 if (HeapTupleIsValid(tp))
3766 {
3767 Form_pg_range rngtup = (Form_pg_range) GETSTRUCT(tp);
3768 Oid result;
3769
3770 result = rngtup->rngmultitypid;
3771 ReleaseSysCache(tp);
3772 return result;
3773 }
3774 else
3775 return InvalidOid;
3776 }
3777
3778 /*
3779 * get_multirange_range
3780 * Returns the range type of a given multirange
3781 *
3782 * Returns InvalidOid if the type is not a multirange.
3783 */
3784 Oid
3785 get_multirange_range(Oid multirangeOid)
3786 {
3787 HeapTuple tp;
3788
3789 tp = SearchSysCache1(RANGEMULTIRANGE, ObjectIdGetDatum(multirangeOid));
3790 if (HeapTupleIsValid(tp))
3791 {
3792 Form_pg_range rngtup = (Form_pg_range) GETSTRUCT(tp);
3793 Oid result;
3794
3795 result = rngtup->rngtypid;
3796 ReleaseSysCache(tp);
3797 return result;
3798 }
3799 else
3800 return InvalidOid;
3801 }
3802
3803 /* ---------- PG_INDEX CACHE ---------- */
3804
3805 /*
3806 * get_index_column_opclass
3807 *
3808 * Given the index OID and column number,
3809 * return opclass of the index column
3810 * or InvalidOid if the index was not found
3811 * or column is non-key one.
3812 */
3813 Oid
3814 get_index_column_opclass(Oid index_oid, int attno)
3815 {
3816 HeapTuple tuple;
3817 Form_pg_index rd_index;
3818 Datum datum;
3819 oidvector *indclass;
3820 Oid opclass;
3821
3822 /* First we need to know the column's opclass. */
3823
3824 tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(index_oid));
3825 if (!HeapTupleIsValid(tuple))
3826 return InvalidOid;
3827
3828 rd_index = (Form_pg_index) GETSTRUCT(tuple);
3829
3830 /* caller is supposed to guarantee this */
3831 Assert(attno > 0 && attno <= rd_index->indnatts);
3832
3833 /* Non-key attributes don't have an opclass */
3834 if (attno > rd_index->indnkeyatts)
3835 {
3836 ReleaseSysCache(tuple);
3837 return InvalidOid;
3838 }
3839
3840 datum = SysCacheGetAttrNotNull(INDEXRELID, tuple, Anum_pg_index_indclass);
3841 indclass = ((oidvector *) DatumGetPointer(datum));
3842
3843 Assert(attno <= indclass->dim1);
3844 opclass = indclass->values[attno - 1];
3845
3846 ReleaseSysCache(tuple);
3847
3848 return opclass;
3849 }
3850
3851 /*
3852 * get_index_isreplident
3853 *
3854 * Given the index OID, return pg_index.indisreplident.
3855 */
3856 bool
3857 get_index_isreplident(Oid index_oid)
3858 {
3859 HeapTuple tuple;
3860 Form_pg_index rd_index;
3861 bool result;
3862
3863 tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(index_oid));
3864 if (!HeapTupleIsValid(tuple))
3865 return false;
3866
3867 rd_index = (Form_pg_index) GETSTRUCT(tuple);
3868 result = rd_index->indisreplident;
3869 ReleaseSysCache(tuple);
3870
3871 return result;
3872 }
3873
3874 /*
3875 * get_index_isvalid
3876 *
3877 * Given the index OID, return pg_index.indisvalid.
3878 */
3879 bool
3880 get_index_isvalid(Oid index_oid)
3881 {
3882 bool isvalid;
3883 HeapTuple tuple;
3884 Form_pg_index rd_index;
3885
3886 tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(index_oid));
3887 if (!HeapTupleIsValid(tuple))
3888 elog(ERROR, "cache lookup failed for index %u", index_oid);
3889
3890 rd_index = (Form_pg_index) GETSTRUCT(tuple);
3891 isvalid = rd_index->indisvalid;
3892 ReleaseSysCache(tuple);
3893
3894 return isvalid;
3895 }
3896
3897 /*
3898 * get_index_isclustered
3899 *
3900 * Given the index OID, return pg_index.indisclustered.
3901 */
3902 bool
3903 get_index_isclustered(Oid index_oid)
3904 {
3905 bool isclustered;
3906 HeapTuple tuple;
3907 Form_pg_index rd_index;
3908
3909 tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(index_oid));
3910 if (!HeapTupleIsValid(tuple))
3911 elog(ERROR, "cache lookup failed for index %u", index_oid);
3912
3913 rd_index = (Form_pg_index) GETSTRUCT(tuple);
3914 isclustered = rd_index->indisclustered;
3915 ReleaseSysCache(tuple);
3916
3917 return isclustered;
3918 }
3919
3920 /*
3921 * get_publication_oid - given a publication name, look up the OID
3922 *
3923 * If missing_ok is false, throw an error if name not found. If true, just
3924 * return InvalidOid.
3925 */
3926 Oid
3927 get_publication_oid(const char *pubname, bool missing_ok)
3928 {
3929 Oid oid;
3930
3931 oid = GetSysCacheOid1(PUBLICATIONNAME, Anum_pg_publication_oid,
3932 CStringGetDatum(pubname));
3933 if (!OidIsValid(oid) && !missing_ok)
3934 ereport(ERROR,
3935 (errcode(ERRCODE_UNDEFINED_OBJECT),
3936 errmsg("publication \"%s\" does not exist", pubname)));
3937 return oid;
3938 }
3939
3940 /*
3941 * get_publication_name - given a publication Oid, look up the name
3942 *
3943 * If missing_ok is false, throw an error if name not found. If true, just
3944 * return NULL.
3945 */
3946 char *
3947 get_publication_name(Oid pubid, bool missing_ok)
3948 {
3949 HeapTuple tup;
3950 char *pubname;
3951 Form_pg_publication pubform;
3952
3953 tup = SearchSysCache1(PUBLICATIONOID, ObjectIdGetDatum(pubid));
3954
3955 if (!HeapTupleIsValid(tup))
3956 {
3957 if (!missing_ok)
3958 elog(ERROR, "cache lookup failed for publication %u", pubid);
3959 return NULL;
3960 }
3961
3962 pubform = (Form_pg_publication) GETSTRUCT(tup);
3963 pubname = pstrdup(NameStr(pubform->pubname));
3964
3965 ReleaseSysCache(tup);
3966
3967 return pubname;
3968 }
3969
3970 /*
3971 * get_subscription_oid - given a subscription name, look up the OID
3972 *
3973 * If missing_ok is false, throw an error if name not found. If true, just
3974 * return InvalidOid.
3975 */
3976 Oid
3977 get_subscription_oid(const char *subname, bool missing_ok)
3978 {
3979 Oid oid;
3980
3981 oid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
3982 MyDatabaseId, CStringGetDatum(subname));
3983 if (!OidIsValid(oid) && !missing_ok)
3984 ereport(ERROR,
3985 (errcode(ERRCODE_UNDEFINED_OBJECT),
3986 errmsg("subscription \"%s\" does not exist", subname)));
3987 return oid;
3988 }
3989
3990 /*
3991 * get_subscription_name - given a subscription OID, look up the name
3992 *
3993 * If missing_ok is false, throw an error if name not found. If true, just
3994 * return NULL.
3995 */
3996 char *
3997 get_subscription_name(Oid subid, bool missing_ok)
3998 {
3999 HeapTuple tup;
4000 char *subname;
4001 Form_pg_subscription subform;
4002
4003 tup = SearchSysCache1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
4004
4005 if (!HeapTupleIsValid(tup))
4006 {
4007 if (!missing_ok)
4008 elog(ERROR, "cache lookup failed for subscription %u", subid);
4009 return NULL;
4010 }
4011
4012 subform = (Form_pg_subscription) GETSTRUCT(tup);
4013 subname = pstrdup(NameStr(subform->subname));
4014
4015 ReleaseSysCache(tup);
4016
4017 return subname;
4018 }