Debian Codegraph @

src/backend/parser/parse_coerce.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * parse_coerce.c
4 * handle type coercions/conversions for parser
5 *
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/parser/parse_coerce.c
12 *
13 *-------------------------------------------------------------------------
14 */
15 #include "postgres.h"
16
17 #include "catalog/pg_cast.h"
18 #include "catalog/pg_class.h"
19 #include "catalog/pg_inherits.h"
20 #include "catalog/pg_proc.h"
21 #include "catalog/pg_type.h"
22 #include "nodes/makefuncs.h"
23 #include "nodes/nodeFuncs.h"
24 #include "parser/parse_coerce.h"
25 #include "parser/parse_relation.h"
26 #include "parser/parse_type.h"
27 #include "utils/builtins.h"
28 #include "utils/datum.h" /* needed for datumIsEqual() */
29 #include "utils/fmgroids.h"
30 #include "utils/lsyscache.h"
31 #include "utils/syscache.h"
32 #include "utils/typcache.h"
33
34
35 static Node *coerce_type_typmod(Node *node,
36 Oid targetTypeId, int32 targetTypMod,
37 CoercionContext ccontext, CoercionForm cformat,
38 int location,
39 bool hideInputCoercion);
40 static void hide_coercion_node(Node *node);
41 static Node *build_coercion_expression(Node *node,
42 CoercionPathType pathtype,
43 Oid funcId,
44 Oid targetTypeId, int32 targetTypMod,
45 CoercionContext ccontext, CoercionForm cformat,
46 int location);
47 static Node *coerce_record_to_complex(ParseState *pstate, Node *node,
48 Oid targetTypeId,
49 CoercionContext ccontext,
50 CoercionForm cformat,
51 int location);
52 static bool is_complex_array(Oid typid);
53 static bool typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId);
54
55
56 /*
57 * coerce_to_target_type()
58 * Convert an expression to a target type and typmod.
59 *
60 * This is the general-purpose entry point for arbitrary type coercion
61 * operations. Direct use of the component operations can_coerce_type,
62 * coerce_type, and coerce_type_typmod should be restricted to special
63 * cases (eg, when the conversion is expected to succeed).
64 *
65 * Returns the possibly-transformed expression tree, or NULL if the type
66 * conversion is not possible. (We do this, rather than ereport'ing directly,
67 * so that callers can generate custom error messages indicating context.)
68 *
69 * pstate - parse state (can be NULL, see coerce_type)
70 * expr - input expression tree (already transformed by transformExpr)
71 * exprtype - result type of expr
72 * targettype - desired result type
73 * targettypmod - desired result typmod
74 * ccontext, cformat - context indicators to control coercions
75 * location - parse location of the coercion request, or -1 if unknown/implicit
76 */
77 Node *
78 coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype,
79 Oid targettype, int32 targettypmod,
80 CoercionContext ccontext,
81 CoercionForm cformat,
82 int location)
83 {
84 Node *result;
85 Node *origexpr;
86
87 if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
88 return NULL;
89
90 /*
91 * If the input has a CollateExpr at the top, strip it off, perform the
92 * coercion, and put a new one back on. This is annoying since it
93 * duplicates logic in coerce_type, but if we don't do this then it's too
94 * hard to tell whether coerce_type actually changed anything, and we
95 * *must* know that to avoid possibly calling hide_coercion_node on
96 * something that wasn't generated by coerce_type. Note that if there are
97 * multiple stacked CollateExprs, we just discard all but the topmost.
98 * Also, if the target type isn't collatable, we discard the CollateExpr.
99 */
100 origexpr = expr;
101 while (expr && IsA(expr, CollateExpr))
102 expr = (Node *) ((CollateExpr *) expr)->arg;
103
104 result = coerce_type(pstate, expr, exprtype,
105 targettype, targettypmod,
106 ccontext, cformat, location);
107
108 /*
109 * If the target is a fixed-length type, it may need a length coercion as
110 * well as a type coercion. If we find ourselves adding both, force the
111 * inner coercion node to implicit display form.
112 */
113 result = coerce_type_typmod(result,
114 targettype, targettypmod,
115 ccontext, cformat, location,
116 (result != expr && !IsA(result, Const)));
117
118 if (expr != origexpr && type_is_collatable(targettype))
119 {
120 /* Reinstall top CollateExpr */
121 CollateExpr *coll = (CollateExpr *) origexpr;
122 CollateExpr *newcoll = makeNode(CollateExpr);
123
124 newcoll->arg = (Expr *) result;
125 newcoll->collOid = coll->collOid;
126 newcoll->location = coll->location;
127 result = (Node *) newcoll;
128 }
129
130 return result;
131 }
132
133
134 /*
135 * coerce_type()
136 * Convert an expression to a different type.
137 *
138 * The caller should already have determined that the coercion is possible;
139 * see can_coerce_type.
140 *
141 * Normally, no coercion to a typmod (length) is performed here. The caller
142 * must call coerce_type_typmod as well, if a typmod constraint is wanted.
143 * (But if the target type is a domain, it may internally contain a
144 * typmod constraint, which will be applied inside coerce_to_domain.)
145 * In some cases pg_cast specifies a type coercion function that also
146 * applies length conversion, and in those cases only, the result will
147 * already be properly coerced to the specified typmod.
148 *
149 * pstate is only used in the case that we are able to resolve the type of
150 * a previously UNKNOWN Param. It is okay to pass pstate = NULL if the
151 * caller does not want type information updated for Params.
152 *
153 * Note: this function must not modify the given expression tree, only add
154 * decoration on top of it. See transformSetOperationTree, for example.
155 */
156 Node *
157 coerce_type(ParseState *pstate, Node *node,
158 Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
159 CoercionContext ccontext, CoercionForm cformat, int location)
160 {
161 Node *result;
162 CoercionPathType pathtype;
163 Oid funcId;
164
165 if (targetTypeId == inputTypeId ||
166 node == NULL)
167 {
168 /* no conversion needed */
169 return node;
170 }
171 if (targetTypeId == ANYOID ||
172 targetTypeId == ANYELEMENTOID ||
173 targetTypeId == ANYNONARRAYOID ||
174 targetTypeId == ANYCOMPATIBLEOID ||
175 targetTypeId == ANYCOMPATIBLENONARRAYOID)
176 {
177 /*
178 * Assume can_coerce_type verified that implicit coercion is okay.
179 *
180 * Note: by returning the unmodified node here, we are saying that
181 * it's OK to treat an UNKNOWN constant as a valid input for a
182 * function accepting one of these pseudotypes. This should be all
183 * right, since an UNKNOWN value is still a perfectly valid Datum.
184 *
185 * NB: we do NOT want a RelabelType here: the exposed type of the
186 * function argument must be its actual type, not the polymorphic
187 * pseudotype.
188 */
189 return node;
190 }
191 if (targetTypeId == ANYARRAYOID ||
192 targetTypeId == ANYENUMOID ||
193 targetTypeId == ANYRANGEOID ||
194 targetTypeId == ANYMULTIRANGEOID ||
195 targetTypeId == ANYCOMPATIBLEARRAYOID ||
196 targetTypeId == ANYCOMPATIBLERANGEOID ||
197 targetTypeId == ANYCOMPATIBLEMULTIRANGEOID)
198 {
199 /*
200 * Assume can_coerce_type verified that implicit coercion is okay.
201 *
202 * These cases are unlike the ones above because the exposed type of
203 * the argument must be an actual array, enum, range, or multirange
204 * type. In particular the argument must *not* be an UNKNOWN
205 * constant. If it is, we just fall through; below, we'll call the
206 * pseudotype's input function, which will produce an error. Also, if
207 * what we have is a domain over array, enum, range, or multirange, we
208 * have to relabel it to its base type.
209 *
210 * Note: currently, we can't actually see a domain-over-enum here,
211 * since the other functions in this file will not match such a
212 * parameter to ANYENUM. But that should get changed eventually.
213 */
214 if (inputTypeId != UNKNOWNOID)
215 {
216 Oid baseTypeId = getBaseType(inputTypeId);
217
218 if (baseTypeId != inputTypeId)
219 {
220 RelabelType *r = makeRelabelType((Expr *) node,
221 baseTypeId, -1,
222 InvalidOid,
223 cformat);
224
225 r->location = location;
226 return (Node *) r;
227 }
228 /* Not a domain type, so return it as-is */
229 return node;
230 }
231 }
232 if (inputTypeId == UNKNOWNOID && IsA(node, Const))
233 {
234 /*
235 * Input is a string constant with previously undetermined type. Apply
236 * the target type's typinput function to it to produce a constant of
237 * the target type.
238 *
239 * NOTE: this case cannot be folded together with the other
240 * constant-input case, since the typinput function does not
241 * necessarily behave the same as a type conversion function. For
242 * example, int4's typinput function will reject "1.2", whereas
243 * float-to-int type conversion will round to integer.
244 *
245 * XXX if the typinput function is not immutable, we really ought to
246 * postpone evaluation of the function call until runtime. But there
247 * is no way to represent a typinput function call as an expression
248 * tree, because C-string values are not Datums. (XXX This *is*
249 * possible as of 7.3, do we want to do it?)
250 */
251 Const *con = (Const *) node;
252 Const *newcon = makeNode(Const);
253 Oid baseTypeId;
254 int32 baseTypeMod;
255 int32 inputTypeMod;
256 Type baseType;
257 ParseCallbackState pcbstate;
258
259 /*
260 * If the target type is a domain, we want to call its base type's
261 * input routine, not domain_in(). This is to avoid premature failure
262 * when the domain applies a typmod: existing input routines follow
263 * implicit-coercion semantics for length checks, which is not always
264 * what we want here. The needed check will be applied properly
265 * inside coerce_to_domain().
266 */
267 baseTypeMod = targetTypeMod;
268 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
269
270 /*
271 * For most types we pass typmod -1 to the input routine, because
272 * existing input routines follow implicit-coercion semantics for
273 * length checks, which is not always what we want here. Any length
274 * constraint will be applied later by our caller. An exception
275 * however is the INTERVAL type, for which we *must* pass the typmod
276 * or it won't be able to obey the bizarre SQL-spec input rules. (Ugly
277 * as sin, but so is this part of the spec...)
278 */
279 if (baseTypeId == INTERVALOID)
280 inputTypeMod = baseTypeMod;
281 else
282 inputTypeMod = -1;
283
284 baseType = typeidType(baseTypeId);
285
286 newcon->consttype = baseTypeId;
287 newcon->consttypmod = inputTypeMod;
288 newcon->constcollid = typeTypeCollation(baseType);
289 newcon->constlen = typeLen(baseType);
290 newcon->constbyval = typeByVal(baseType);
291 newcon->constisnull = con->constisnull;
292
293 /*
294 * We use the original literal's location regardless of the position
295 * of the coercion. This is a change from pre-9.2 behavior, meant to
296 * simplify life for pg_stat_statements.
297 */
298 newcon->location = con->location;
299
300 /*
301 * Set up to point at the constant's text if the input routine throws
302 * an error.
303 */
304 setup_parser_errposition_callback(&pcbstate, pstate, con->location);
305
306 /*
307 * We assume here that UNKNOWN's internal representation is the same
308 * as CSTRING.
309 */
310 if (!con->constisnull)
311 newcon->constvalue = stringTypeDatum(baseType,
312 DatumGetCString(con->constvalue),
313 inputTypeMod);
314 else
315 newcon->constvalue = stringTypeDatum(baseType,
316 NULL,
317 inputTypeMod);
318
319 /*
320 * If it's a varlena value, force it to be in non-expanded
321 * (non-toasted) format; this avoids any possible dependency on
322 * external values and improves consistency of representation.
323 */
324 if (!con->constisnull && newcon->constlen == -1)
325 newcon->constvalue =
326 PointerGetDatum(PG_DETOAST_DATUM(newcon->constvalue));
327
328 #ifdef RANDOMIZE_ALLOCATED_MEMORY
329
330 /*
331 * For pass-by-reference data types, repeat the conversion to see if
332 * the input function leaves any uninitialized bytes in the result. We
333 * can only detect that reliably if RANDOMIZE_ALLOCATED_MEMORY is
334 * enabled, so we don't bother testing otherwise. The reason we don't
335 * want any instability in the input function is that comparison of
336 * Const nodes relies on bytewise comparison of the datums, so if the
337 * input function leaves garbage then subexpressions that should be
338 * identical may not get recognized as such. See pgsql-hackers
339 * discussion of 2008-04-04.
340 */
341 if (!con->constisnull && !newcon->constbyval)
342 {
343 Datum val2;
344
345 val2 = stringTypeDatum(baseType,
346 DatumGetCString(con->constvalue),
347 inputTypeMod);
348 if (newcon->constlen == -1)
349 val2 = PointerGetDatum(PG_DETOAST_DATUM(val2));
350 if (!datumIsEqual(newcon->constvalue, val2, false, newcon->constlen))
351 elog(WARNING, "type %s has unstable input conversion for \"%s\"",
352 typeTypeName(baseType), DatumGetCString(con->constvalue));
353 }
354 #endif
355
356 cancel_parser_errposition_callback(&pcbstate);
357
358 result = (Node *) newcon;
359
360 /* If target is a domain, apply constraints. */
361 if (baseTypeId != targetTypeId)
362 result = coerce_to_domain(result,
363 baseTypeId, baseTypeMod,
364 targetTypeId,
365 ccontext, cformat, location,
366 false);
367
368 ReleaseSysCache(baseType);
369
370 return result;
371 }
372 if (IsA(node, Param) &&
373 pstate != NULL && pstate->p_coerce_param_hook != NULL)
374 {
375 /*
376 * Allow the CoerceParamHook to decide what happens. It can return a
377 * transformed node (very possibly the same Param node), or return
378 * NULL to indicate we should proceed with normal coercion.
379 */
380 result = pstate->p_coerce_param_hook(pstate,
381 (Param *) node,
382 targetTypeId,
383 targetTypeMod,
384 location);
385 if (result)
386 return result;
387 }
388 if (IsA(node, CollateExpr))
389 {
390 /*
391 * If we have a COLLATE clause, we have to push the coercion
392 * underneath the COLLATE; or discard the COLLATE if the target type
393 * isn't collatable. This is really ugly, but there is little choice
394 * because the above hacks on Consts and Params wouldn't happen
395 * otherwise. This kluge has consequences in coerce_to_target_type.
396 */
397 CollateExpr *coll = (CollateExpr *) node;
398
399 result = coerce_type(pstate, (Node *) coll->arg,
400 inputTypeId, targetTypeId, targetTypeMod,
401 ccontext, cformat, location);
402 if (type_is_collatable(targetTypeId))
403 {
404 CollateExpr *newcoll = makeNode(CollateExpr);
405
406 newcoll->arg = (Expr *) result;
407 newcoll->collOid = coll->collOid;
408 newcoll->location = coll->location;
409 result = (Node *) newcoll;
410 }
411 return result;
412 }
413 pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
414 &funcId);
415 if (pathtype != COERCION_PATH_NONE)
416 {
417 Oid baseTypeId;
418 int32 baseTypeMod;
419
420 baseTypeMod = targetTypeMod;
421 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
422
423 if (pathtype != COERCION_PATH_RELABELTYPE)
424 {
425 /*
426 * Generate an expression tree representing run-time application
427 * of the conversion function. If we are dealing with a domain
428 * target type, the conversion function will yield the base type,
429 * and we need to extract the correct typmod to use from the
430 * domain's typtypmod.
431 */
432 result = build_coercion_expression(node, pathtype, funcId,
433 baseTypeId, baseTypeMod,
434 ccontext, cformat, location);
435
436 /*
437 * If domain, coerce to the domain type and relabel with domain
438 * type ID, hiding the previous coercion node.
439 */
440 if (targetTypeId != baseTypeId)
441 result = coerce_to_domain(result, baseTypeId, baseTypeMod,
442 targetTypeId,
443 ccontext, cformat, location,
444 true);
445 }
446 else
447 {
448 /*
449 * We don't need to do a physical conversion, but we do need to
450 * attach a RelabelType node so that the expression will be seen
451 * to have the intended type when inspected by higher-level code.
452 *
453 * Also, domains may have value restrictions beyond the base type
454 * that must be accounted for. If the destination is a domain
455 * then we won't need a RelabelType node.
456 */
457 result = coerce_to_domain(node, baseTypeId, baseTypeMod,
458 targetTypeId,
459 ccontext, cformat, location,
460 false);
461 if (result == node)
462 {
463 /*
464 * XXX could we label result with exprTypmod(node) instead of
465 * default -1 typmod, to save a possible length-coercion
466 * later? Would work if both types have same interpretation of
467 * typmod, which is likely but not certain.
468 */
469 RelabelType *r = makeRelabelType((Expr *) result,
470 targetTypeId, -1,
471 InvalidOid,
472 cformat);
473
474 r->location = location;
475 result = (Node *) r;
476 }
477 }
478 return result;
479 }
480 if (inputTypeId == RECORDOID &&
481 ISCOMPLEX(targetTypeId))
482 {
483 /* Coerce a RECORD to a specific complex type */
484 return coerce_record_to_complex(pstate, node, targetTypeId,
485 ccontext, cformat, location);
486 }
487 if (targetTypeId == RECORDOID &&
488 ISCOMPLEX(inputTypeId))
489 {
490 /* Coerce a specific complex type to RECORD */
491 /* NB: we do NOT want a RelabelType here */
492 return node;
493 }
494 #ifdef NOT_USED
495 if (inputTypeId == RECORDARRAYOID &&
496 is_complex_array(targetTypeId))
497 {
498 /* Coerce record[] to a specific complex array type */
499 /* not implemented yet ... */
500 }
501 #endif
502 if (targetTypeId == RECORDARRAYOID &&
503 is_complex_array(inputTypeId))
504 {
505 /* Coerce a specific complex array type to record[] */
506 /* NB: we do NOT want a RelabelType here */
507 return node;
508 }
509 if (typeInheritsFrom(inputTypeId, targetTypeId)
510 || typeIsOfTypedTable(inputTypeId, targetTypeId))
511 {
512 /*
513 * Input class type is a subclass of target, so generate an
514 * appropriate runtime conversion (removing unneeded columns and
515 * possibly rearranging the ones that are wanted).
516 *
517 * We will also get here when the input is a domain over a subclass of
518 * the target type. To keep life simple for the executor, we define
519 * ConvertRowtypeExpr as only working between regular composite types;
520 * therefore, in such cases insert a RelabelType to smash the input
521 * expression down to its base type.
522 */
523 Oid baseTypeId = getBaseType(inputTypeId);
524 ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
525
526 if (baseTypeId != inputTypeId)
527 {
528 RelabelType *rt = makeRelabelType((Expr *) node,
529 baseTypeId, -1,
530 InvalidOid,
531 COERCE_IMPLICIT_CAST);
532
533 rt->location = location;
534 node = (Node *) rt;
535 }
536 r->arg = (Expr *) node;
537 r->resulttype = targetTypeId;
538 r->convertformat = cformat;
539 r->location = location;
540 return (Node *) r;
541 }
542 /* If we get here, caller blew it */
543 elog(ERROR, "failed to find conversion function from %s to %s",
544 format_type_be(inputTypeId), format_type_be(targetTypeId));
545 return NULL; /* keep compiler quiet */
546 }
547
548
549 /*
550 * can_coerce_type()
551 * Can input_typeids be coerced to target_typeids?
552 *
553 * We must be told the context (CAST construct, assignment, implicit coercion)
554 * as this determines the set of available casts.
555 */
556 bool
557 can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids,
558 CoercionContext ccontext)
559 {
560 bool have_generics = false;
561 int i;
562
563 /* run through argument list... */
564 for (i = 0; i < nargs; i++)
565 {
566 Oid inputTypeId = input_typeids[i];
567 Oid targetTypeId = target_typeids[i];
568 CoercionPathType pathtype;
569 Oid funcId;
570
571 /* no problem if same type */
572 if (inputTypeId == targetTypeId)
573 continue;
574
575 /* reject all cases of casting something else to/from "internal" */
576 if (inputTypeId == INTERNALOID || targetTypeId == INTERNALOID)
577 return false;
578
579 /* accept if target is ANY */
580 if (targetTypeId == ANYOID)
581 continue;
582
583 /* accept if target is polymorphic, for now */
584 if (IsPolymorphicType(targetTypeId))
585 {
586 have_generics = true; /* do more checking later */
587 continue;
588 }
589
590 /*
591 * If input is an untyped string constant, assume we can convert it to
592 * anything.
593 */
594 if (inputTypeId == UNKNOWNOID)
595 continue;
596
597 /*
598 * If pg_cast shows that we can coerce, accept. This test now covers
599 * both binary-compatible and coercion-function cases.
600 */
601 pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
602 &funcId);
603 if (pathtype != COERCION_PATH_NONE)
604 continue;
605
606 /*
607 * If input is RECORD and target is a composite type, assume we can
608 * coerce (may need tighter checking here)
609 */
610 if (inputTypeId == RECORDOID &&
611 ISCOMPLEX(targetTypeId))
612 continue;
613
614 /*
615 * If input is a composite type and target is RECORD, accept
616 */
617 if (targetTypeId == RECORDOID &&
618 ISCOMPLEX(inputTypeId))
619 continue;
620
621 #ifdef NOT_USED /* not implemented yet */
622
623 /*
624 * If input is record[] and target is a composite array type, assume
625 * we can coerce (may need tighter checking here)
626 */
627 if (inputTypeId == RECORDARRAYOID &&
628 is_complex_array(targetTypeId))
629 continue;
630 #endif
631
632 /*
633 * If input is a composite array type and target is record[], accept
634 */
635 if (targetTypeId == RECORDARRAYOID &&
636 is_complex_array(inputTypeId))
637 continue;
638
639 /*
640 * If input is a class type that inherits from target, accept
641 */
642 if (typeInheritsFrom(inputTypeId, targetTypeId)
643 || typeIsOfTypedTable(inputTypeId, targetTypeId))
644 continue;
645
646 /*
647 * Else, cannot coerce at this argument position
648 */
649 return false;
650 }
651
652 /* If we found any generic argument types, cross-check them */
653 if (have_generics)
654 {
655 if (!check_generic_type_consistency(input_typeids, target_typeids,
656 nargs))
657 return false;
658 }
659
660 return true;
661 }
662
663
664 /*
665 * Create an expression tree to represent coercion to a domain type.
666 *
667 * 'arg': input expression
668 * 'baseTypeId': base type of domain
669 * 'baseTypeMod': base type typmod of domain
670 * 'typeId': target type to coerce to
671 * 'ccontext': context indicator to control coercions
672 * 'cformat': coercion display format
673 * 'location': coercion request location
674 * 'hideInputCoercion': if true, hide the input coercion under this one.
675 *
676 * If the target type isn't a domain, the given 'arg' is returned as-is.
677 */
678 Node *
679 coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId,
680 CoercionContext ccontext, CoercionForm cformat, int location,
681 bool hideInputCoercion)
682 {
683 CoerceToDomain *result;
684
685 /* We now require the caller to supply correct baseTypeId/baseTypeMod */
686 Assert(OidIsValid(baseTypeId));
687
688 /* If it isn't a domain, return the node as it was passed in */
689 if (baseTypeId == typeId)
690 return arg;
691
692 /* Suppress display of nested coercion steps */
693 if (hideInputCoercion)
694 hide_coercion_node(arg);
695
696 /*
697 * If the domain applies a typmod to its base type, build the appropriate
698 * coercion step. Mark it implicit for display purposes, because we don't
699 * want it shown separately by ruleutils.c; but the isExplicit flag passed
700 * to the conversion function depends on the manner in which the domain
701 * coercion is invoked, so that the semantics of implicit and explicit
702 * coercion differ. (Is that really the behavior we want?)
703 *
704 * NOTE: because we apply this as part of the fixed expression structure,
705 * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that that
706 * would be safe to do anyway, without lots of knowledge about what the
707 * base type thinks the typmod means.
708 */
709 arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
710 ccontext, COERCE_IMPLICIT_CAST, location,
711 false);
712
713 /*
714 * Now build the domain coercion node. This represents run-time checking
715 * of any constraints currently attached to the domain. This also ensures
716 * that the expression is properly labeled as to result type.
717 */
718 result = makeNode(CoerceToDomain);
719 result->arg = (Expr *) arg;
720 result->resulttype = typeId;
721 result->resulttypmod = -1; /* currently, always -1 for domains */
722 /* resultcollid will be set by parse_collate.c */
723 result->coercionformat = cformat;
724 result->location = location;
725
726 return (Node *) result;
727 }
728
729
730 /*
731 * coerce_type_typmod()
732 * Force a value to a particular typmod, if meaningful and possible.
733 *
734 * This is applied to values that are going to be stored in a relation
735 * (where we have an atttypmod for the column) as well as values being
736 * explicitly CASTed (where the typmod comes from the target type spec).
737 *
738 * The caller must have already ensured that the value is of the correct
739 * type, typically by applying coerce_type.
740 *
741 * ccontext may affect semantics, depending on whether the length coercion
742 * function pays attention to the isExplicit flag it's passed.
743 *
744 * cformat determines the display properties of the generated node (if any).
745 *
746 * If hideInputCoercion is true *and* we generate a node, the input node is
747 * forced to IMPLICIT display form, so that only the typmod coercion node will
748 * be visible when displaying the expression.
749 *
750 * NOTE: this does not need to work on domain types, because any typmod
751 * coercion for a domain is considered to be part of the type coercion
752 * needed to produce the domain value in the first place. So, no getBaseType.
753 */
754 static Node *
755 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
756 CoercionContext ccontext, CoercionForm cformat,
757 int location,
758 bool hideInputCoercion)
759 {
760 CoercionPathType pathtype;
761 Oid funcId;
762
763 /* Skip coercion if already done */
764 if (targetTypMod == exprTypmod(node))
765 return node;
766
767 /* Suppress display of nested coercion steps */
768 if (hideInputCoercion)
769 hide_coercion_node(node);
770
771 /*
772 * A negative typmod means that no actual coercion is needed, but we still
773 * want a RelabelType to ensure that the expression exposes the intended
774 * typmod.
775 */
776 if (targetTypMod < 0)
777 pathtype = COERCION_PATH_NONE;
778 else
779 pathtype = find_typmod_coercion_function(targetTypeId, &funcId);
780
781 if (pathtype != COERCION_PATH_NONE)
782 {
783 node = build_coercion_expression(node, pathtype, funcId,
784 targetTypeId, targetTypMod,
785 ccontext, cformat, location);
786 }
787 else
788 {
789 /*
790 * We don't need to perform any actual coercion step, but we should
791 * apply a RelabelType to ensure that the expression exposes the
792 * intended typmod.
793 */
794 node = applyRelabelType(node, targetTypeId, targetTypMod,
795 exprCollation(node),
796 cformat, location, false);
797 }
798
799 return node;
800 }
801
802 /*
803 * Mark a coercion node as IMPLICIT so it will never be displayed by
804 * ruleutils.c. We use this when we generate a nest of coercion nodes
805 * to implement what is logically one conversion; the inner nodes are
806 * forced to IMPLICIT_CAST format. This does not change their semantics,
807 * only display behavior.
808 *
809 * It is caller error to call this on something that doesn't have a
810 * CoercionForm field.
811 */
812 static void
813 hide_coercion_node(Node *node)
814 {
815 if (IsA(node, FuncExpr))
816 ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
817 else if (IsA(node, RelabelType))
818 ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
819 else if (IsA(node, CoerceViaIO))
820 ((CoerceViaIO *) node)->coerceformat = COERCE_IMPLICIT_CAST;
821 else if (IsA(node, ArrayCoerceExpr))
822 ((ArrayCoerceExpr *) node)->coerceformat = COERCE_IMPLICIT_CAST;
823 else if (IsA(node, ConvertRowtypeExpr))
824 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
825 else if (IsA(node, RowExpr))
826 ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
827 else if (IsA(node, CoerceToDomain))
828 ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
829 else
830 elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
831 }
832
833 /*
834 * build_coercion_expression()
835 * Construct an expression tree for applying a pg_cast entry.
836 *
837 * This is used for both type-coercion and length-coercion operations,
838 * since there is no difference in terms of the calling convention.
839 */
840 static Node *
841 build_coercion_expression(Node *node,
842 CoercionPathType pathtype,
843 Oid funcId,
844 Oid targetTypeId, int32 targetTypMod,
845 CoercionContext ccontext, CoercionForm cformat,
846 int location)
847 {
848 int nargs = 0;
849
850 if (OidIsValid(funcId))
851 {
852 HeapTuple tp;
853 Form_pg_proc procstruct;
854
855 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcId));
856 if (!HeapTupleIsValid(tp))
857 elog(ERROR, "cache lookup failed for function %u", funcId);
858 procstruct = (Form_pg_proc) GETSTRUCT(tp);
859
860 /*
861 * These Asserts essentially check that function is a legal coercion
862 * function. We can't make the seemingly obvious tests on prorettype
863 * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
864 * various binary-compatibility cases.
865 */
866 /* Assert(targetTypeId == procstruct->prorettype); */
867 Assert(!procstruct->proretset);
868 Assert(procstruct->prokind == PROKIND_FUNCTION);
869 nargs = procstruct->pronargs;
870 Assert(nargs >= 1 && nargs <= 3);
871 /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
872 Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
873 Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
874
875 ReleaseSysCache(tp);
876 }
877
878 if (pathtype == COERCION_PATH_FUNC)
879 {
880 /* We build an ordinary FuncExpr with special arguments */
881 FuncExpr *fexpr;
882 List *args;
883 Const *cons;
884
885 Assert(OidIsValid(funcId));
886
887 args = list_make1(node);
888
889 if (nargs >= 2)
890 {
891 /* Pass target typmod as an int4 constant */
892 cons = makeConst(INT4OID,
893 -1,
894 InvalidOid,
895 sizeof(int32),
896 Int32GetDatum(targetTypMod),
897 false,
898 true);
899
900 args = lappend(args, cons);
901 }
902
903 if (nargs == 3)
904 {
905 /* Pass it a boolean isExplicit parameter, too */
906 cons = makeConst(BOOLOID,
907 -1,
908 InvalidOid,
909 sizeof(bool),
910 BoolGetDatum(ccontext == COERCION_EXPLICIT),
911 false,
912 true);
913
914 args = lappend(args, cons);
915 }
916
917 fexpr = makeFuncExpr(funcId, targetTypeId, args,
918 InvalidOid, InvalidOid, cformat);
919 fexpr->location = location;
920 return (Node *) fexpr;
921 }
922 else if (pathtype == COERCION_PATH_ARRAYCOERCE)
923 {
924 /* We need to build an ArrayCoerceExpr */
925 ArrayCoerceExpr *acoerce = makeNode(ArrayCoerceExpr);
926 CaseTestExpr *ctest = makeNode(CaseTestExpr);
927 Oid sourceBaseTypeId;
928 int32 sourceBaseTypeMod;
929 Oid targetElementType;
930 Node *elemexpr;
931
932 /*
933 * Look through any domain over the source array type. Note we don't
934 * expect that the target type is a domain; it must be a plain array.
935 * (To get to a domain target type, we'll do coerce_to_domain later.)
936 */
937 sourceBaseTypeMod = exprTypmod(node);
938 sourceBaseTypeId = getBaseTypeAndTypmod(exprType(node),
939 &sourceBaseTypeMod);
940
941 /*
942 * Set up a CaseTestExpr representing one element of the source array.
943 * This is an abuse of CaseTestExpr, but it's OK as long as there
944 * can't be any CaseExpr or ArrayCoerceExpr within the completed
945 * elemexpr.
946 */
947 ctest->typeId = get_element_type(sourceBaseTypeId);
948 Assert(OidIsValid(ctest->typeId));
949 ctest->typeMod = sourceBaseTypeMod;
950 ctest->collation = InvalidOid; /* Assume coercions don't care */
951
952 /* And coerce it to the target element type */
953 targetElementType = get_element_type(targetTypeId);
954 Assert(OidIsValid(targetElementType));
955
956 elemexpr = coerce_to_target_type(NULL,
957 (Node *) ctest,
958 ctest->typeId,
959 targetElementType,
960 targetTypMod,
961 ccontext,
962 cformat,
963 location);
964 if (elemexpr == NULL) /* shouldn't happen */
965 elog(ERROR, "failed to coerce array element type as expected");
966
967 acoerce->arg = (Expr *) node;
968 acoerce->elemexpr = (Expr *) elemexpr;
969 acoerce->resulttype = targetTypeId;
970
971 /*
972 * Label the output as having a particular element typmod only if we
973 * ended up with a per-element expression that is labeled that way.
974 */
975 acoerce->resulttypmod = exprTypmod(elemexpr);
976 /* resultcollid will be set by parse_collate.c */
977 acoerce->coerceformat = cformat;
978 acoerce->location = location;
979
980 return (Node *) acoerce;
981 }
982 else if (pathtype == COERCION_PATH_COERCEVIAIO)
983 {
984 /* We need to build a CoerceViaIO node */
985 CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
986
987 Assert(!OidIsValid(funcId));
988
989 iocoerce->arg = (Expr *) node;
990 iocoerce->resulttype = targetTypeId;
991 /* resultcollid will be set by parse_collate.c */
992 iocoerce->coerceformat = cformat;
993 iocoerce->location = location;
994
995 return (Node *) iocoerce;
996 }
997 else
998 {
999 elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
1000 (int) pathtype);
1001 return NULL; /* keep compiler quiet */
1002 }
1003 }
1004
1005
1006 /*
1007 * coerce_record_to_complex
1008 * Coerce a RECORD to a specific composite type.
1009 *
1010 * Currently we only support this for inputs that are RowExprs or whole-row
1011 * Vars.
1012 */
1013 static Node *
1014 coerce_record_to_complex(ParseState *pstate, Node *node,
1015 Oid targetTypeId,
1016 CoercionContext ccontext,
1017 CoercionForm cformat,
1018 int location)
1019 {
1020 RowExpr *rowexpr;
1021 Oid baseTypeId;
1022 int32 baseTypeMod = -1;
1023 TupleDesc tupdesc;
1024 List *args = NIL;
1025 List *newargs;
1026 int i;
1027 int ucolno;
1028 ListCell *arg;
1029
1030 if (node && IsA(node, RowExpr))
1031 {
1032 /*
1033 * Since the RowExpr must be of type RECORD, we needn't worry about it
1034 * containing any dropped columns.
1035 */
1036 args = ((RowExpr *) node)->args;
1037 }
1038 else if (node && IsA(node, Var) &&
1039 ((Var *) node)->varattno == InvalidAttrNumber)
1040 {
1041 Var *var = (Var *) node;
1042 ParseNamespaceItem *nsitem;
1043
1044 nsitem = GetNSItemByVar(pstate, var);
1045 args = expandNSItemVars(pstate, nsitem, var->varlevelsup,
1046 var->location, NULL);
1047 }
1048 else
1049 ereport(ERROR,
1050 (errcode(ERRCODE_CANNOT_COERCE),
1051 errmsg("cannot cast type %s to %s",
1052 format_type_be(RECORDOID),
1053 format_type_be(targetTypeId)),
1054 parser_coercion_errposition(pstate, location, node)));
1055
1056 /*
1057 * Look up the composite type, accounting for possibility that what we are
1058 * given is a domain over composite.
1059 */
1060 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
1061 tupdesc = lookup_rowtype_tupdesc(baseTypeId, baseTypeMod);
1062
1063 /* Process the fields */
1064 newargs = NIL;
1065 ucolno = 1;
1066 arg = list_head(args);
1067 for (i = 0; i < tupdesc->natts; i++)
1068 {
1069 Node *expr;
1070 Node *cexpr;
1071 Oid exprtype;
1072 Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1073
1074 /* Fill in NULLs for dropped columns in rowtype */
1075 if (attr->attisdropped)
1076 {
1077 /*
1078 * can't use atttypid here, but it doesn't really matter what type
1079 * the Const claims to be.
1080 */
1081 newargs = lappend(newargs,
1082 makeNullConst(INT4OID, -1, InvalidOid));
1083 continue;
1084 }
1085
1086 if (arg == NULL)
1087 ereport(ERROR,
1088 (errcode(ERRCODE_CANNOT_COERCE),
1089 errmsg("cannot cast type %s to %s",
1090 format_type_be(RECORDOID),
1091 format_type_be(targetTypeId)),
1092 errdetail("Input has too few columns."),
1093 parser_coercion_errposition(pstate, location, node)));
1094 expr = (Node *) lfirst(arg);
1095 exprtype = exprType(expr);
1096
1097 cexpr = coerce_to_target_type(pstate,
1098 expr, exprtype,
1099 attr->atttypid,
1100 attr->atttypmod,
1101 ccontext,
1102 COERCE_IMPLICIT_CAST,
1103 -1);
1104 if (cexpr == NULL)
1105 ereport(ERROR,
1106 (errcode(ERRCODE_CANNOT_COERCE),
1107 errmsg("cannot cast type %s to %s",
1108 format_type_be(RECORDOID),
1109 format_type_be(targetTypeId)),
1110 errdetail("Cannot cast type %s to %s in column %d.",
1111 format_type_be(exprtype),
1112 format_type_be(attr->atttypid),
1113 ucolno),
1114 parser_coercion_errposition(pstate, location, expr)));
1115 newargs = lappend(newargs, cexpr);
1116 ucolno++;
1117 arg = lnext(args, arg);
1118 }
1119 if (arg != NULL)
1120 ereport(ERROR,
1121 (errcode(ERRCODE_CANNOT_COERCE),
1122 errmsg("cannot cast type %s to %s",
1123 format_type_be(RECORDOID),
1124 format_type_be(targetTypeId)),
1125 errdetail("Input has too many columns."),
1126 parser_coercion_errposition(pstate, location, node)));
1127
1128 ReleaseTupleDesc(tupdesc);
1129
1130 rowexpr = makeNode(RowExpr);
1131 rowexpr->args = newargs;
1132 rowexpr->row_typeid = baseTypeId;
1133 rowexpr->row_format = cformat;
1134 rowexpr->colnames = NIL; /* not needed for named target type */
1135 rowexpr->location = location;
1136
1137 /* If target is a domain, apply constraints */
1138 if (baseTypeId != targetTypeId)
1139 {
1140 rowexpr->row_format = COERCE_IMPLICIT_CAST;
1141 return coerce_to_domain((Node *) rowexpr,
1142 baseTypeId, baseTypeMod,
1143 targetTypeId,
1144 ccontext, cformat, location,
1145 false);
1146 }
1147
1148 return (Node *) rowexpr;
1149 }
1150
1151 /*
1152 * coerce_to_boolean()
1153 * Coerce an argument of a construct that requires boolean input
1154 * (AND, OR, NOT, etc). Also check that input is not a set.
1155 *
1156 * Returns the possibly-transformed node tree.
1157 *
1158 * As with coerce_type, pstate may be NULL if no special unknown-Param
1159 * processing is wanted.
1160 */
1161 Node *
1162 coerce_to_boolean(ParseState *pstate, Node *node,
1163 const char *constructName)
1164 {
1165 Oid inputTypeId = exprType(node);
1166
1167 if (inputTypeId != BOOLOID)
1168 {
1169 Node *newnode;
1170
1171 newnode = coerce_to_target_type(pstate, node, inputTypeId,
1172 BOOLOID, -1,
1173 COERCION_ASSIGNMENT,
1174 COERCE_IMPLICIT_CAST,
1175 -1);
1176 if (newnode == NULL)
1177 ereport(ERROR,
1178 (errcode(ERRCODE_DATATYPE_MISMATCH),
1179 /* translator: first %s is name of a SQL construct, eg WHERE */
1180 errmsg("argument of %s must be type %s, not type %s",
1181 constructName, "boolean",
1182 format_type_be(inputTypeId)),
1183 parser_errposition(pstate, exprLocation(node))));
1184 node = newnode;
1185 }
1186
1187 if (expression_returns_set(node))
1188 ereport(ERROR,
1189 (errcode(ERRCODE_DATATYPE_MISMATCH),
1190 /* translator: %s is name of a SQL construct, eg WHERE */
1191 errmsg("argument of %s must not return a set",
1192 constructName),
1193 parser_errposition(pstate, exprLocation(node))));
1194
1195 return node;
1196 }
1197
1198 /*
1199 * coerce_to_specific_type_typmod()
1200 * Coerce an argument of a construct that requires a specific data type,
1201 * with a specific typmod. Also check that input is not a set.
1202 *
1203 * Returns the possibly-transformed node tree.
1204 *
1205 * As with coerce_type, pstate may be NULL if no special unknown-Param
1206 * processing is wanted.
1207 */
1208 Node *
1209 coerce_to_specific_type_typmod(ParseState *pstate, Node *node,
1210 Oid targetTypeId, int32 targetTypmod,
1211 const char *constructName)
1212 {
1213 Oid inputTypeId = exprType(node);
1214
1215 if (inputTypeId != targetTypeId)
1216 {
1217 Node *newnode;
1218
1219 newnode = coerce_to_target_type(pstate, node, inputTypeId,
1220 targetTypeId, targetTypmod,
1221 COERCION_ASSIGNMENT,
1222 COERCE_IMPLICIT_CAST,
1223 -1);
1224 if (newnode == NULL)
1225 ereport(ERROR,
1226 (errcode(ERRCODE_DATATYPE_MISMATCH),
1227 /* translator: first %s is name of a SQL construct, eg LIMIT */
1228 errmsg("argument of %s must be type %s, not type %s",
1229 constructName,
1230 format_type_be(targetTypeId),
1231 format_type_be(inputTypeId)),
1232 parser_errposition(pstate, exprLocation(node))));
1233 node = newnode;
1234 }
1235
1236 if (expression_returns_set(node))
1237 ereport(ERROR,
1238 (errcode(ERRCODE_DATATYPE_MISMATCH),
1239 /* translator: %s is name of a SQL construct, eg LIMIT */
1240 errmsg("argument of %s must not return a set",
1241 constructName),
1242 parser_errposition(pstate, exprLocation(node))));
1243
1244 return node;
1245 }
1246
1247 /*
1248 * coerce_to_specific_type()
1249 * Coerce an argument of a construct that requires a specific data type.
1250 * Also check that input is not a set.
1251 *
1252 * Returns the possibly-transformed node tree.
1253 *
1254 * As with coerce_type, pstate may be NULL if no special unknown-Param
1255 * processing is wanted.
1256 */
1257 Node *
1258 coerce_to_specific_type(ParseState *pstate, Node *node,
1259 Oid targetTypeId,
1260 const char *constructName)
1261 {
1262 return coerce_to_specific_type_typmod(pstate, node,
1263 targetTypeId, -1,
1264 constructName);
1265 }
1266
1267 /*
1268 * coerce_null_to_domain()
1269 * Build a NULL constant, then wrap it in CoerceToDomain
1270 * if the desired type is a domain type. This allows any
1271 * NOT NULL domain constraint to be enforced at runtime.
1272 */
1273 Node *
1274 coerce_null_to_domain(Oid typid, int32 typmod, Oid collation,
1275 int typlen, bool typbyval)
1276 {
1277 Node *result;
1278 Oid baseTypeId;
1279 int32 baseTypeMod = typmod;
1280
1281 /*
1282 * The constant must appear to have the domain's base type/typmod, else
1283 * coerce_to_domain() will apply a length coercion which is useless.
1284 */
1285 baseTypeId = getBaseTypeAndTypmod(typid, &baseTypeMod);
1286 result = (Node *) makeConst(baseTypeId,
1287 baseTypeMod,
1288 collation,
1289 typlen,
1290 (Datum) 0,
1291 true, /* isnull */
1292 typbyval);
1293 if (typid != baseTypeId)
1294 result = coerce_to_domain(result,
1295 baseTypeId, baseTypeMod,
1296 typid,
1297 COERCION_IMPLICIT,
1298 COERCE_IMPLICIT_CAST,
1299 -1,
1300 false);
1301 return result;
1302 }
1303
1304 /*
1305 * parser_coercion_errposition - report coercion error location, if possible
1306 *
1307 * We prefer to point at the coercion request (CAST, ::, etc) if possible;
1308 * but there may be no such location in the case of an implicit coercion.
1309 * In that case point at the input expression.
1310 *
1311 * XXX possibly this is more generally useful than coercion errors;
1312 * if so, should rename and place with parser_errposition.
1313 */
1314 int
1315 parser_coercion_errposition(ParseState *pstate,
1316 int coerce_location,
1317 Node *input_expr)
1318 {
1319 if (coerce_location >= 0)
1320 return parser_errposition(pstate, coerce_location);
1321 else
1322 return parser_errposition(pstate, exprLocation(input_expr));
1323 }
1324
1325
1326 /*
1327 * select_common_type()
1328 * Determine the common supertype of a list of input expressions.
1329 * This is used for determining the output type of CASE, UNION,
1330 * and similar constructs.
1331 *
1332 * 'exprs' is a *nonempty* list of expressions. Note that earlier items
1333 * in the list will be preferred if there is doubt.
1334 * 'context' is a phrase to use in the error message if we fail to select
1335 * a usable type. Pass NULL to have the routine return InvalidOid
1336 * rather than throwing an error on failure.
1337 * 'which_expr': if not NULL, receives a pointer to the particular input
1338 * expression from which the result type was taken.
1339 *
1340 * Caution: "failure" just means that there were inputs of different type
1341 * categories. It is not guaranteed that all the inputs are coercible to the
1342 * selected type; caller must check that (see verify_common_type).
1343 */
1344 Oid
1345 select_common_type(ParseState *pstate, List *exprs, const char *context,
1346 Node **which_expr)
1347 {
1348 Node *pexpr;
1349 Oid ptype;
1350 TYPCATEGORY pcategory;
1351 bool pispreferred;
1352 ListCell *lc;
1353
1354 Assert(exprs != NIL);
1355 pexpr = (Node *) linitial(exprs);
1356 lc = list_second_cell(exprs);
1357 ptype = exprType(pexpr);
1358
1359 /*
1360 * If all input types are valid and exactly the same, just pick that type.
1361 * This is the only way that we will resolve the result as being a domain
1362 * type; otherwise domains are smashed to their base types for comparison.
1363 */
1364 if (ptype != UNKNOWNOID)
1365 {
1366 for_each_cell(lc, exprs, lc)
1367 {
1368 Node *nexpr = (Node *) lfirst(lc);
1369 Oid ntype = exprType(nexpr);
1370
1371 if (ntype != ptype)
1372 break;
1373 }
1374 if (lc == NULL) /* got to the end of the list? */
1375 {
1376 if (which_expr)
1377 *which_expr = pexpr;
1378 return ptype;
1379 }
1380 }
1381
1382 /*
1383 * Nope, so set up for the full algorithm. Note that at this point, lc
1384 * points to the first list item with type different from pexpr's; we need
1385 * not re-examine any items the previous loop advanced over.
1386 */
1387 ptype = getBaseType(ptype);
1388 get_type_category_preferred(ptype, &pcategory, &pispreferred);
1389
1390 for_each_cell(lc, exprs, lc)
1391 {
1392 Node *nexpr = (Node *) lfirst(lc);
1393 Oid ntype = getBaseType(exprType(nexpr));
1394
1395 /* move on to next one if no new information... */
1396 if (ntype != UNKNOWNOID && ntype != ptype)
1397 {
1398 TYPCATEGORY ncategory;
1399 bool nispreferred;
1400
1401 get_type_category_preferred(ntype, &ncategory, &nispreferred);
1402 if (ptype == UNKNOWNOID)
1403 {
1404 /* so far, only unknowns so take anything... */
1405 pexpr = nexpr;
1406 ptype = ntype;
1407 pcategory = ncategory;
1408 pispreferred = nispreferred;
1409 }
1410 else if (ncategory != pcategory)
1411 {
1412 /*
1413 * both types in different categories? then not much hope...
1414 */
1415 if (context == NULL)
1416 return InvalidOid;
1417 ereport(ERROR,
1418 (errcode(ERRCODE_DATATYPE_MISMATCH),
1419 /*------
1420 translator: first %s is name of a SQL construct, eg CASE */
1421 errmsg("%s types %s and %s cannot be matched",
1422 context,
1423 format_type_be(ptype),
1424 format_type_be(ntype)),
1425 parser_errposition(pstate, exprLocation(nexpr))));
1426 }
1427 else if (!pispreferred &&
1428 can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1429 !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1430 {
1431 /*
1432 * take new type if can coerce to it implicitly but not the
1433 * other way; but if we have a preferred type, stay on it.
1434 */
1435 pexpr = nexpr;
1436 ptype = ntype;
1437 pcategory = ncategory;
1438 pispreferred = nispreferred;
1439 }
1440 }
1441 }
1442
1443 /*
1444 * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1445 * then resolve as type TEXT. This situation comes up with constructs
1446 * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1447 * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1448 * output type as UNKNOWN, but that really doesn't work, because we'd
1449 * probably end up needing a runtime coercion from UNKNOWN to something
1450 * else, and we usually won't have it. We need to coerce the unknown
1451 * literals while they are still literals, so a decision has to be made
1452 * now.
1453 */
1454 if (ptype == UNKNOWNOID)
1455 ptype = TEXTOID;
1456
1457 if (which_expr)
1458 *which_expr = pexpr;
1459 return ptype;
1460 }
1461
1462 /*
1463 * select_common_type_from_oids()
1464 * Determine the common supertype of an array of type OIDs.
1465 *
1466 * This is the same logic as select_common_type(), but working from
1467 * an array of type OIDs not a list of expressions. As in that function,
1468 * earlier entries in the array have some preference over later ones.
1469 * On failure, return InvalidOid if noerror is true, else throw an error.
1470 *
1471 * Caution: "failure" just means that there were inputs of different type
1472 * categories. It is not guaranteed that all the inputs are coercible to the
1473 * selected type; caller must check that (see verify_common_type_from_oids).
1474 *
1475 * Note: neither caller will pass any UNKNOWNOID entries, so the tests
1476 * for that in this function are dead code. However, they don't cost much,
1477 * and it seems better to keep this logic as close to select_common_type()
1478 * as possible.
1479 */
1480 static Oid
1481 select_common_type_from_oids(int nargs, const Oid *typeids, bool noerror)
1482 {
1483 Oid ptype;
1484 TYPCATEGORY pcategory;
1485 bool pispreferred;
1486 int i = 1;
1487
1488 Assert(nargs > 0);
1489 ptype = typeids[0];
1490
1491 /* If all input types are valid and exactly the same, pick that type. */
1492 if (ptype != UNKNOWNOID)
1493 {
1494 for (; i < nargs; i++)
1495 {
1496 if (typeids[i] != ptype)
1497 break;
1498 }
1499 if (i == nargs)
1500 return ptype;
1501 }
1502
1503 /*
1504 * Nope, so set up for the full algorithm. Note that at this point, we
1505 * can skip array entries before "i"; they are all equal to ptype.
1506 */
1507 ptype = getBaseType(ptype);
1508 get_type_category_preferred(ptype, &pcategory, &pispreferred);
1509
1510 for (; i < nargs; i++)
1511 {
1512 Oid ntype = getBaseType(typeids[i]);
1513
1514 /* move on to next one if no new information... */
1515 if (ntype != UNKNOWNOID && ntype != ptype)
1516 {
1517 TYPCATEGORY ncategory;
1518 bool nispreferred;
1519
1520 get_type_category_preferred(ntype, &ncategory, &nispreferred);
1521 if (ptype == UNKNOWNOID)
1522 {
1523 /* so far, only unknowns so take anything... */
1524 ptype = ntype;
1525 pcategory = ncategory;
1526 pispreferred = nispreferred;
1527 }
1528 else if (ncategory != pcategory)
1529 {
1530 /*
1531 * both types in different categories? then not much hope...
1532 */
1533 if (noerror)
1534 return InvalidOid;
1535 ereport(ERROR,
1536 (errcode(ERRCODE_DATATYPE_MISMATCH),
1537 errmsg("argument types %s and %s cannot be matched",
1538 format_type_be(ptype),
1539 format_type_be(ntype))));
1540 }
1541 else if (!pispreferred &&
1542 can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1543 !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1544 {
1545 /*
1546 * take new type if can coerce to it implicitly but not the
1547 * other way; but if we have a preferred type, stay on it.
1548 */
1549 ptype = ntype;
1550 pcategory = ncategory;
1551 pispreferred = nispreferred;
1552 }
1553 }
1554 }
1555
1556 /* Like select_common_type(), choose TEXT if all inputs were UNKNOWN */
1557 if (ptype == UNKNOWNOID)
1558 ptype = TEXTOID;
1559
1560 return ptype;
1561 }
1562
1563 /*
1564 * coerce_to_common_type()
1565 * Coerce an expression to the given type.
1566 *
1567 * This is used following select_common_type() to coerce the individual
1568 * expressions to the desired type. 'context' is a phrase to use in the
1569 * error message if we fail to coerce.
1570 *
1571 * As with coerce_type, pstate may be NULL if no special unknown-Param
1572 * processing is wanted.
1573 */
1574 Node *
1575 coerce_to_common_type(ParseState *pstate, Node *node,
1576 Oid targetTypeId, const char *context)
1577 {
1578 Oid inputTypeId = exprType(node);
1579
1580 if (inputTypeId == targetTypeId)
1581 return node; /* no work */
1582 if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
1583 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1584 COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
1585 else
1586 ereport(ERROR,
1587 (errcode(ERRCODE_CANNOT_COERCE),
1588 /* translator: first %s is name of a SQL construct, eg CASE */
1589 errmsg("%s could not convert type %s to %s",
1590 context,
1591 format_type_be(inputTypeId),
1592 format_type_be(targetTypeId)),
1593 parser_errposition(pstate, exprLocation(node))));
1594 return node;
1595 }
1596
1597 /*
1598 * verify_common_type()
1599 * Verify that all input types can be coerced to a proposed common type.
1600 * Return true if so, false if not all coercions are possible.
1601 *
1602 * Most callers of select_common_type() don't need to do this explicitly
1603 * because the checks will happen while trying to convert input expressions
1604 * to the right type, e.g. in coerce_to_common_type(). However, if a separate
1605 * check step is needed to validate the applicability of the common type, call
1606 * this.
1607 */
1608 bool
1609 verify_common_type(Oid common_type, List *exprs)
1610 {
1611 ListCell *lc;
1612
1613 foreach(lc, exprs)
1614 {
1615 Node *nexpr = (Node *) lfirst(lc);
1616 Oid ntype = exprType(nexpr);
1617
1618 if (!can_coerce_type(1, &ntype, &common_type, COERCION_IMPLICIT))
1619 return false;
1620 }
1621 return true;
1622 }
1623
1624 /*
1625 * verify_common_type_from_oids()
1626 * As above, but work from an array of type OIDs.
1627 */
1628 static bool
1629 verify_common_type_from_oids(Oid common_type, int nargs, const Oid *typeids)
1630 {
1631 for (int i = 0; i < nargs; i++)
1632 {
1633 if (!can_coerce_type(1, &typeids[i], &common_type, COERCION_IMPLICIT))
1634 return false;
1635 }
1636 return true;
1637 }
1638
1639 /*
1640 * select_common_typmod()
1641 * Determine the common typmod of a list of input expressions.
1642 *
1643 * common_type is the selected common type of the expressions, typically
1644 * computed using select_common_type().
1645 */
1646 int32
1647 select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
1648 {
1649 ListCell *lc;
1650 bool first = true;
1651 int32 result = -1;
1652
1653 foreach(lc, exprs)
1654 {
1655 Node *expr = (Node *) lfirst(lc);
1656
1657 /* Types must match */
1658 if (exprType(expr) != common_type)
1659 return -1;
1660 else if (first)
1661 {
1662 result = exprTypmod(expr);
1663 first = false;
1664 }
1665 else
1666 {
1667 /* As soon as we see a non-matching typmod, fall back to -1 */
1668 if (result != exprTypmod(expr))
1669 return -1;
1670 }
1671 }
1672
1673 return result;
1674 }
1675
1676 /*
1677 * check_generic_type_consistency()
1678 * Are the actual arguments potentially compatible with a
1679 * polymorphic function?
1680 *
1681 * The argument consistency rules are:
1682 *
1683 * 1) All arguments declared ANYELEMENT must have the same datatype.
1684 * 2) All arguments declared ANYARRAY must have the same datatype,
1685 * which must be a varlena array type.
1686 * 3) All arguments declared ANYRANGE must be the same range type.
1687 * Similarly, all arguments declared ANYMULTIRANGE must be the same
1688 * multirange type; and if both of these appear, the ANYRANGE type
1689 * must be the element type of the ANYMULTIRANGE type.
1690 * 4) If there are arguments of more than one of these polymorphic types,
1691 * the array element type and/or range subtype must be the same as each
1692 * other and the same as the ANYELEMENT type.
1693 * 5) ANYENUM is treated the same as ANYELEMENT except that if it is used
1694 * (alone or in combination with plain ANYELEMENT), we add the extra
1695 * condition that the ANYELEMENT type must be an enum.
1696 * 6) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1697 * we add the extra condition that the ANYELEMENT type must not be an array.
1698 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1699 * is an extra restriction if not.)
1700 * 7) All arguments declared ANYCOMPATIBLE must be implicitly castable
1701 * to a common supertype (chosen as per select_common_type's rules).
1702 * ANYCOMPATIBLENONARRAY works like ANYCOMPATIBLE but also requires the
1703 * common supertype to not be an array. If there are ANYCOMPATIBLEARRAY
1704 * or ANYCOMPATIBLERANGE or ANYCOMPATIBLEMULTIRANGE arguments, their element
1705 * types or subtypes are included while making the choice of common supertype.
1706 * 8) The resolved type of ANYCOMPATIBLEARRAY arguments will be the array
1707 * type over the common supertype (which might not be the same array type
1708 * as any of the original arrays).
1709 * 9) All ANYCOMPATIBLERANGE arguments must be the exact same range type
1710 * (after domain flattening), since we have no preference rule that would
1711 * let us choose one over another. Furthermore, that range's subtype
1712 * must exactly match the common supertype chosen by rule 7.
1713 * 10) All ANYCOMPATIBLEMULTIRANGE arguments must be the exact same multirange
1714 * type (after domain flattening), since we have no preference rule that
1715 * would let us choose one over another. Furthermore, if ANYCOMPATIBLERANGE
1716 * also appears, that range type must be the multirange's element type;
1717 * otherwise, the multirange's range's subtype must exactly match the
1718 * common supertype chosen by rule 7.
1719 *
1720 * Domains over arrays match ANYARRAY, and are immediately flattened to their
1721 * base type. (Thus, for example, we will consider it a match if one ANYARRAY
1722 * argument is a domain over int4[] while another one is just int4[].) Also
1723 * notice that such a domain does *not* match ANYNONARRAY. The same goes
1724 * for ANYCOMPATIBLEARRAY and ANYCOMPATIBLENONARRAY.
1725 *
1726 * Similarly, domains over ranges match ANYRANGE or ANYCOMPATIBLERANGE,
1727 * and are immediately flattened to their base type. Likewise, domains
1728 * over multiranges match ANYMULTIRANGE or ANYCOMPATIBLEMULTIRANGE and are
1729 * immediately flattened to their base type.
1730 *
1731 * Note that domains aren't currently considered to match ANYENUM,
1732 * even if their base type would match.
1733 *
1734 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1735 * argument, assume it is okay.
1736 *
1737 * We do not ereport here, but just return false if a rule is violated.
1738 */
1739 bool
1740 check_generic_type_consistency(const Oid *actual_arg_types,
1741 const Oid *declared_arg_types,
1742 int nargs)
1743 {
1744 Oid elem_typeid = InvalidOid;
1745 Oid array_typeid = InvalidOid;
1746 Oid range_typeid = InvalidOid;
1747 Oid multirange_typeid = InvalidOid;
1748 Oid anycompatible_range_typeid = InvalidOid;
1749 Oid anycompatible_range_typelem = InvalidOid;
1750 Oid anycompatible_multirange_typeid = InvalidOid;
1751 Oid anycompatible_multirange_typelem = InvalidOid;
1752 Oid range_typelem = InvalidOid;
1753 bool have_anynonarray = false;
1754 bool have_anyenum = false;
1755 bool have_anycompatible_nonarray = false;
1756 int n_anycompatible_args = 0;
1757 Oid anycompatible_actual_types[FUNC_MAX_ARGS];
1758
1759 /*
1760 * Loop through the arguments to see if we have any that are polymorphic.
1761 * If so, require the actual types to be consistent.
1762 */
1763 Assert(nargs <= FUNC_MAX_ARGS);
1764 for (int j = 0; j < nargs; j++)
1765 {
1766 Oid decl_type = declared_arg_types[j];
1767 Oid actual_type = actual_arg_types[j];
1768
1769 if (decl_type == ANYELEMENTOID ||
1770 decl_type == ANYNONARRAYOID ||
1771 decl_type == ANYENUMOID)
1772 {
1773 if (decl_type == ANYNONARRAYOID)
1774 have_anynonarray = true;
1775 else if (decl_type == ANYENUMOID)
1776 have_anyenum = true;
1777 if (actual_type == UNKNOWNOID)
1778 continue;
1779 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1780 return false;
1781 elem_typeid = actual_type;
1782 }
1783 else if (decl_type == ANYARRAYOID)
1784 {
1785 if (actual_type == UNKNOWNOID)
1786 continue;
1787 actual_type = getBaseType(actual_type); /* flatten domains */
1788 if (OidIsValid(array_typeid) && actual_type != array_typeid)
1789 return false;
1790 array_typeid = actual_type;
1791 }
1792 else if (decl_type == ANYRANGEOID)
1793 {
1794 if (actual_type == UNKNOWNOID)
1795 continue;
1796 actual_type = getBaseType(actual_type); /* flatten domains */
1797 if (OidIsValid(range_typeid) && actual_type != range_typeid)
1798 return false;
1799 range_typeid = actual_type;
1800 }
1801 else if (decl_type == ANYMULTIRANGEOID)
1802 {
1803 if (actual_type == UNKNOWNOID)
1804 continue;
1805 actual_type = getBaseType(actual_type); /* flatten domains */
1806 if (OidIsValid(multirange_typeid) && actual_type != multirange_typeid)
1807 return false;
1808 multirange_typeid = actual_type;
1809 }
1810 else if (decl_type == ANYCOMPATIBLEOID ||
1811 decl_type == ANYCOMPATIBLENONARRAYOID)
1812 {
1813 if (decl_type == ANYCOMPATIBLENONARRAYOID)
1814 have_anycompatible_nonarray = true;
1815 if (actual_type == UNKNOWNOID)
1816 continue;
1817 /* collect the actual types of non-unknown COMPATIBLE args */
1818 anycompatible_actual_types[n_anycompatible_args++] = actual_type;
1819 }
1820 else if (decl_type == ANYCOMPATIBLEARRAYOID)
1821 {
1822 Oid elem_type;
1823
1824 if (actual_type == UNKNOWNOID)
1825 continue;
1826 actual_type = getBaseType(actual_type); /* flatten domains */
1827 elem_type = get_element_type(actual_type);
1828 if (!OidIsValid(elem_type))
1829 return false; /* not an array */
1830 /* collect the element type for common-supertype choice */
1831 anycompatible_actual_types[n_anycompatible_args++] = elem_type;
1832 }
1833 else if (decl_type == ANYCOMPATIBLERANGEOID)
1834 {
1835 if (actual_type == UNKNOWNOID)
1836 continue;
1837 actual_type = getBaseType(actual_type); /* flatten domains */
1838 if (OidIsValid(anycompatible_range_typeid))
1839 {
1840 /* All ANYCOMPATIBLERANGE arguments must be the same type */
1841 if (anycompatible_range_typeid != actual_type)
1842 return false;
1843 }
1844 else
1845 {
1846 anycompatible_range_typeid = actual_type;
1847 anycompatible_range_typelem = get_range_subtype(actual_type);
1848 if (!OidIsValid(anycompatible_range_typelem))
1849 return false; /* not a range type */
1850 /* collect the subtype for common-supertype choice */
1851 anycompatible_actual_types[n_anycompatible_args++] = anycompatible_range_typelem;
1852 }
1853 }
1854 else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
1855 {
1856 if (actual_type == UNKNOWNOID)
1857 continue;
1858 actual_type = getBaseType(actual_type); /* flatten domains */
1859 if (OidIsValid(anycompatible_multirange_typeid))
1860 {
1861 /* All ANYCOMPATIBLEMULTIRANGE arguments must be the same type */
1862 if (anycompatible_multirange_typeid != actual_type)
1863 return false;
1864 }
1865 else
1866 {
1867 anycompatible_multirange_typeid = actual_type;
1868 anycompatible_multirange_typelem = get_multirange_range(actual_type);
1869 if (!OidIsValid(anycompatible_multirange_typelem))
1870 return false; /* not a multirange type */
1871 /* we'll consider the subtype below */
1872 }
1873 }
1874 }
1875
1876 /* Get the element type based on the array type, if we have one */
1877 if (OidIsValid(array_typeid))
1878 {
1879 if (array_typeid == ANYARRAYOID)
1880 {
1881 /*
1882 * Special case for matching ANYARRAY input to an ANYARRAY
1883 * argument: allow it for now. enforce_generic_type_consistency()
1884 * might complain later, depending on the presence of other
1885 * polymorphic arguments or results, but it will deliver a less
1886 * surprising error message than "function does not exist".
1887 *
1888 * (If you think to change this, note that can_coerce_type will
1889 * consider such a situation as a match, so that we might not even
1890 * get here.)
1891 */
1892 }
1893 else
1894 {
1895 Oid array_typelem;
1896
1897 array_typelem = get_element_type(array_typeid);
1898 if (!OidIsValid(array_typelem))
1899 return false; /* should be an array, but isn't */
1900
1901 if (!OidIsValid(elem_typeid))
1902 {
1903 /*
1904 * if we don't have an element type yet, use the one we just
1905 * got
1906 */
1907 elem_typeid = array_typelem;
1908 }
1909 else if (array_typelem != elem_typeid)
1910 {
1911 /* otherwise, they better match */
1912 return false;
1913 }
1914 }
1915 }
1916
1917 /* Deduce range type from multirange type, or check that they agree */
1918 if (OidIsValid(multirange_typeid))
1919 {
1920 Oid multirange_typelem;
1921
1922 multirange_typelem = get_multirange_range(multirange_typeid);
1923 if (!OidIsValid(multirange_typelem))
1924 return false; /* should be a multirange, but isn't */
1925
1926 if (!OidIsValid(range_typeid))
1927 {
1928 /* If we don't have a range type yet, use the one we just got */
1929 range_typeid = multirange_typelem;
1930 range_typelem = get_range_subtype(multirange_typelem);
1931 if (!OidIsValid(range_typelem))
1932 return false; /* should be a range, but isn't */
1933 }
1934 else if (multirange_typelem != range_typeid)
1935 {
1936 /* otherwise, they better match */
1937 return false;
1938 }
1939 }
1940
1941 /* Get the element type based on the range type, if we have one */
1942 if (OidIsValid(range_typeid))
1943 {
1944 range_typelem = get_range_subtype(range_typeid);
1945 if (!OidIsValid(range_typelem))
1946 return false; /* should be a range, but isn't */
1947
1948 if (!OidIsValid(elem_typeid))
1949 {
1950 /*
1951 * If we don't have an element type yet, use the one we just got
1952 */
1953 elem_typeid = range_typelem;
1954 }
1955 else if (range_typelem != elem_typeid)
1956 {
1957 /* otherwise, they better match */
1958 return false;
1959 }
1960 }
1961
1962 if (have_anynonarray)
1963 {
1964 /* require the element type to not be an array or domain over array */
1965 if (type_is_array_domain(elem_typeid))
1966 return false;
1967 }
1968
1969 if (have_anyenum)
1970 {
1971 /* require the element type to be an enum */
1972 if (!type_is_enum(elem_typeid))
1973 return false;
1974 }
1975
1976 /* Deduce range type from multirange type, or check that they agree */
1977 if (OidIsValid(anycompatible_multirange_typeid))
1978 {
1979 if (OidIsValid(anycompatible_range_typeid))
1980 {
1981 if (anycompatible_multirange_typelem !=
1982 anycompatible_range_typeid)
1983 return false;
1984 }
1985 else
1986 {
1987 anycompatible_range_typeid = anycompatible_multirange_typelem;
1988 anycompatible_range_typelem = get_range_subtype(anycompatible_range_typeid);
1989 if (!OidIsValid(anycompatible_range_typelem))
1990 return false; /* not a range type */
1991 /* collect the subtype for common-supertype choice */
1992 anycompatible_actual_types[n_anycompatible_args++] =
1993 anycompatible_range_typelem;
1994 }
1995 }
1996
1997 /* Check matching of ANYCOMPATIBLE-family arguments, if any */
1998 if (n_anycompatible_args > 0)
1999 {
2000 Oid anycompatible_typeid;
2001
2002 anycompatible_typeid =
2003 select_common_type_from_oids(n_anycompatible_args,
2004 anycompatible_actual_types,
2005 true);
2006
2007 if (!OidIsValid(anycompatible_typeid))
2008 return false; /* there's definitely no common supertype */
2009
2010 /* We have to verify that the selected type actually works */
2011 if (!verify_common_type_from_oids(anycompatible_typeid,
2012 n_anycompatible_args,
2013 anycompatible_actual_types))
2014 return false;
2015
2016 if (have_anycompatible_nonarray)
2017 {
2018 /*
2019 * require the anycompatible type to not be an array or domain
2020 * over array
2021 */
2022 if (type_is_array_domain(anycompatible_typeid))
2023 return false;
2024 }
2025
2026 /*
2027 * The anycompatible type must exactly match the range element type,
2028 * if we were able to identify one. This checks compatibility for
2029 * anycompatiblemultirange too since that also sets
2030 * anycompatible_range_typelem above.
2031 */
2032 if (OidIsValid(anycompatible_range_typelem) &&
2033 anycompatible_range_typelem != anycompatible_typeid)
2034 return false;
2035 }
2036
2037 /* Looks valid */
2038 return true;
2039 }
2040
2041 /*
2042 * enforce_generic_type_consistency()
2043 * Make sure a polymorphic function is legally callable, and
2044 * deduce actual argument and result types.
2045 *
2046 * If any polymorphic pseudotype is used in a function's arguments or
2047 * return type, we make sure the actual data types are consistent with
2048 * each other. The argument consistency rules are shown above for
2049 * check_generic_type_consistency().
2050 *
2051 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
2052 * argument, we attempt to deduce the actual type it should have. If
2053 * successful, we alter that position of declared_arg_types[] so that
2054 * make_fn_arguments will coerce the literal to the right thing.
2055 *
2056 * If we have polymorphic arguments of the ANYCOMPATIBLE family,
2057 * we similarly alter declared_arg_types[] entries to show the resolved
2058 * common supertype, so that make_fn_arguments will coerce the actual
2059 * arguments to the proper type.
2060 *
2061 * Rules are applied to the function's return type (possibly altering it)
2062 * if it is declared as a polymorphic type and there is at least one
2063 * polymorphic argument type:
2064 *
2065 * 1) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
2066 * argument's actual type as the function's return type.
2067 * 2) If return type is ANYARRAY, and any argument is ANYARRAY, use the
2068 * argument's actual type as the function's return type.
2069 * 3) Similarly, if return type is ANYRANGE or ANYMULTIRANGE, and any
2070 * argument is ANYRANGE or ANYMULTIRANGE, use that argument's actual type
2071 * (or the corresponding range or multirange type) as the function's return
2072 * type.
2073 * 4) Otherwise, if return type is ANYELEMENT or ANYARRAY, and there is
2074 * at least one ANYELEMENT, ANYARRAY, ANYRANGE, or ANYMULTIRANGE input,
2075 * deduce the return type from those inputs, or throw error if we can't.
2076 * 5) Otherwise, if return type is ANYRANGE or ANYMULTIRANGE, throw error.
2077 * (We have no way to select a specific range type if the arguments don't
2078 * include ANYRANGE or ANYMULTIRANGE.)
2079 * 6) ANYENUM is treated the same as ANYELEMENT except that if it is used
2080 * (alone or in combination with plain ANYELEMENT), we add the extra
2081 * condition that the ANYELEMENT type must be an enum.
2082 * 7) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
2083 * we add the extra condition that the ANYELEMENT type must not be an array.
2084 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
2085 * is an extra restriction if not.)
2086 * 8) ANYCOMPATIBLE, ANYCOMPATIBLEARRAY, and ANYCOMPATIBLENONARRAY are handled
2087 * by resolving the common supertype of those arguments (or their element
2088 * types, for array inputs), and then coercing all those arguments to the
2089 * common supertype, or the array type over the common supertype for
2090 * ANYCOMPATIBLEARRAY.
2091 * 9) For ANYCOMPATIBLERANGE and ANYCOMPATIBLEMULTIRANGE, there must be at
2092 * least one non-UNKNOWN input matching those arguments, and all such
2093 * inputs must be the same range type (or its multirange type, as
2094 * appropriate), since we cannot deduce a range type from non-range types.
2095 * Furthermore, the range type's subtype is included while choosing the
2096 * common supertype for ANYCOMPATIBLE et al, and it must exactly match
2097 * that common supertype.
2098 *
2099 * Domains over arrays or ranges match ANYARRAY or ANYRANGE arguments,
2100 * respectively, and are immediately flattened to their base type. (In
2101 * particular, if the return type is also ANYARRAY or ANYRANGE, we'll set
2102 * it to the base type not the domain type.) The same is true for
2103 * ANYMULTIRANGE, ANYCOMPATIBLEARRAY, ANYCOMPATIBLERANGE, and
2104 * ANYCOMPATIBLEMULTIRANGE.
2105 *
2106 * When allow_poly is false, we are not expecting any of the actual_arg_types
2107 * to be polymorphic, and we should not return a polymorphic result type
2108 * either. When allow_poly is true, it is okay to have polymorphic "actual"
2109 * arg types, and we can return a matching polymorphic type as the result.
2110 * (This case is currently used only to check compatibility of an aggregate's
2111 * declaration with the underlying transfn.)
2112 *
2113 * A special case is that we could see ANYARRAY as an actual_arg_type even
2114 * when allow_poly is false (this is possible only because pg_statistic has
2115 * columns shown as anyarray in the catalogs). We allow this to match a
2116 * declared ANYARRAY argument, but only if there is no other polymorphic
2117 * argument that we would need to match it with, and no need to determine
2118 * the element type to infer the result type. Note this means that functions
2119 * taking ANYARRAY had better behave sanely if applied to the pg_statistic
2120 * columns; they can't just assume that successive inputs are of the same
2121 * actual element type. There is no similar logic for ANYCOMPATIBLEARRAY;
2122 * there isn't a need for it since there are no catalog columns of that type,
2123 * so we won't see it as input. We could consider matching an actual ANYARRAY
2124 * input to an ANYCOMPATIBLEARRAY argument, but at present that seems useless
2125 * as well, since there's no value in using ANYCOMPATIBLEARRAY unless there's
2126 * at least one other ANYCOMPATIBLE-family argument or result.
2127 *
2128 * Also, if there are no arguments declared to be of polymorphic types,
2129 * we'll return the rettype unmodified even if it's polymorphic. This should
2130 * never occur for user-declared functions, because CREATE FUNCTION prevents
2131 * it. But it does happen for some built-in functions, such as array_in().
2132 */
2133 Oid
2134 enforce_generic_type_consistency(const Oid *actual_arg_types,
2135 Oid *declared_arg_types,
2136 int nargs,
2137 Oid rettype,
2138 bool allow_poly)
2139 {
2140 bool have_poly_anycompatible = false;
2141 bool have_poly_unknowns = false;
2142 Oid elem_typeid = InvalidOid;
2143 Oid array_typeid = InvalidOid;
2144 Oid range_typeid = InvalidOid;
2145 Oid multirange_typeid = InvalidOid;
2146 Oid anycompatible_typeid = InvalidOid;
2147 Oid anycompatible_array_typeid = InvalidOid;
2148 Oid anycompatible_range_typeid = InvalidOid;
2149 Oid anycompatible_range_typelem = InvalidOid;
2150 Oid anycompatible_multirange_typeid = InvalidOid;
2151 Oid anycompatible_multirange_typelem = InvalidOid;
2152 bool have_anynonarray = (rettype == ANYNONARRAYOID);
2153 bool have_anyenum = (rettype == ANYENUMOID);
2154 bool have_anymultirange = (rettype == ANYMULTIRANGEOID);
2155 bool have_anycompatible_nonarray = (rettype == ANYCOMPATIBLENONARRAYOID);
2156 bool have_anycompatible_array = (rettype == ANYCOMPATIBLEARRAYOID);
2157 bool have_anycompatible_range = (rettype == ANYCOMPATIBLERANGEOID);
2158 bool have_anycompatible_multirange = (rettype == ANYCOMPATIBLEMULTIRANGEOID);
2159 int n_poly_args = 0; /* this counts all family-1 arguments */
2160 int n_anycompatible_args = 0; /* this counts only non-unknowns */
2161 Oid anycompatible_actual_types[FUNC_MAX_ARGS];
2162
2163 /*
2164 * Loop through the arguments to see if we have any that are polymorphic.
2165 * If so, require the actual types to be consistent.
2166 */
2167 Assert(nargs <= FUNC_MAX_ARGS);
2168 for (int j = 0; j < nargs; j++)
2169 {
2170 Oid decl_type = declared_arg_types[j];
2171 Oid actual_type = actual_arg_types[j];
2172
2173 if (decl_type == ANYELEMENTOID ||
2174 decl_type == ANYNONARRAYOID ||
2175 decl_type == ANYENUMOID)
2176 {
2177 n_poly_args++;
2178 if (decl_type == ANYNONARRAYOID)
2179 have_anynonarray = true;
2180 else if (decl_type == ANYENUMOID)
2181 have_anyenum = true;
2182 if (actual_type == UNKNOWNOID)
2183 {
2184 have_poly_unknowns = true;
2185 continue;
2186 }
2187 if (allow_poly && decl_type == actual_type)
2188 continue; /* no new information here */
2189 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
2190 ereport(ERROR,
2191 (errcode(ERRCODE_DATATYPE_MISMATCH),
2192 errmsg("arguments declared \"%s\" are not all alike", "anyelement"),
2193 errdetail("%s versus %s",
2194 format_type_be(elem_typeid),
2195 format_type_be(actual_type))));
2196 elem_typeid = actual_type;
2197 }
2198 else if (decl_type == ANYARRAYOID)
2199 {
2200 n_poly_args++;
2201 if (actual_type == UNKNOWNOID)
2202 {
2203 have_poly_unknowns = true;
2204 continue;
2205 }
2206 if (allow_poly && decl_type == actual_type)
2207 continue; /* no new information here */
2208 actual_type = getBaseType(actual_type); /* flatten domains */
2209 if (OidIsValid(array_typeid) && actual_type != array_typeid)
2210 ereport(ERROR,
2211 (errcode(ERRCODE_DATATYPE_MISMATCH),
2212 errmsg("arguments declared \"%s\" are not all alike", "anyarray"),
2213 errdetail("%s versus %s",
2214 format_type_be(array_typeid),
2215 format_type_be(actual_type))));
2216 array_typeid = actual_type;
2217 }
2218 else if (decl_type == ANYRANGEOID)
2219 {
2220 n_poly_args++;
2221 if (actual_type == UNKNOWNOID)
2222 {
2223 have_poly_unknowns = true;
2224 continue;
2225 }
2226 if (allow_poly && decl_type == actual_type)
2227 continue; /* no new information here */
2228 actual_type = getBaseType(actual_type); /* flatten domains */
2229 if (OidIsValid(range_typeid) && actual_type != range_typeid)
2230 ereport(ERROR,
2231 (errcode(ERRCODE_DATATYPE_MISMATCH),
2232 errmsg("arguments declared \"%s\" are not all alike", "anyrange"),
2233 errdetail("%s versus %s",
2234 format_type_be(range_typeid),
2235 format_type_be(actual_type))));
2236 range_typeid = actual_type;
2237 }
2238 else if (decl_type == ANYMULTIRANGEOID)
2239 {
2240 n_poly_args++;
2241 have_anymultirange = true;
2242 if (actual_type == UNKNOWNOID)
2243 {
2244 have_poly_unknowns = true;
2245 continue;
2246 }
2247 if (allow_poly && decl_type == actual_type)
2248 continue; /* no new information here */
2249 actual_type = getBaseType(actual_type); /* flatten domains */
2250 if (OidIsValid(multirange_typeid) && actual_type != multirange_typeid)
2251 ereport(ERROR,
2252 (errcode(ERRCODE_DATATYPE_MISMATCH),
2253 errmsg("arguments declared \"%s\" are not all alike", "anymultirange"),
2254 errdetail("%s versus %s",
2255 format_type_be(multirange_typeid),
2256 format_type_be(actual_type))));
2257 multirange_typeid = actual_type;
2258 }
2259 else if (decl_type == ANYCOMPATIBLEOID ||
2260 decl_type == ANYCOMPATIBLENONARRAYOID)
2261 {
2262 have_poly_anycompatible = true;
2263 if (decl_type == ANYCOMPATIBLENONARRAYOID)
2264 have_anycompatible_nonarray = true;
2265 if (actual_type == UNKNOWNOID)
2266 continue;
2267 if (allow_poly && decl_type == actual_type)
2268 continue; /* no new information here */
2269 /* collect the actual types of non-unknown COMPATIBLE args */
2270 anycompatible_actual_types[n_anycompatible_args++] = actual_type;
2271 }
2272 else if (decl_type == ANYCOMPATIBLEARRAYOID)
2273 {
2274 Oid anycompatible_elem_type;
2275
2276 have_poly_anycompatible = true;
2277 have_anycompatible_array = true;
2278 if (actual_type == UNKNOWNOID)
2279 continue;
2280 if (allow_poly && decl_type == actual_type)
2281 continue; /* no new information here */
2282 actual_type = getBaseType(actual_type); /* flatten domains */
2283 anycompatible_elem_type = get_element_type(actual_type);
2284 if (!OidIsValid(anycompatible_elem_type))
2285 ereport(ERROR,
2286 (errcode(ERRCODE_DATATYPE_MISMATCH),
2287 errmsg("argument declared %s is not an array but type %s",
2288 "anycompatiblearray",
2289 format_type_be(actual_type))));
2290 /* collect the element type for common-supertype choice */
2291 anycompatible_actual_types[n_anycompatible_args++] = anycompatible_elem_type;
2292 }
2293 else if (decl_type == ANYCOMPATIBLERANGEOID)
2294 {
2295 have_poly_anycompatible = true;
2296 have_anycompatible_range = true;
2297 if (actual_type == UNKNOWNOID)
2298 continue;
2299 if (allow_poly && decl_type == actual_type)
2300 continue; /* no new information here */
2301 actual_type = getBaseType(actual_type); /* flatten domains */
2302 if (OidIsValid(anycompatible_range_typeid))
2303 {
2304 /* All ANYCOMPATIBLERANGE arguments must be the same type */
2305 if (anycompatible_range_typeid != actual_type)
2306 ereport(ERROR,
2307 (errcode(ERRCODE_DATATYPE_MISMATCH),
2308 errmsg("arguments declared \"%s\" are not all alike", "anycompatiblerange"),
2309 errdetail("%s versus %s",
2310 format_type_be(anycompatible_range_typeid),
2311 format_type_be(actual_type))));
2312 }
2313 else
2314 {
2315 anycompatible_range_typeid = actual_type;
2316 anycompatible_range_typelem = get_range_subtype(actual_type);
2317 if (!OidIsValid(anycompatible_range_typelem))
2318 ereport(ERROR,
2319 (errcode(ERRCODE_DATATYPE_MISMATCH),
2320 errmsg("argument declared %s is not a range type but type %s",
2321 "anycompatiblerange",
2322 format_type_be(actual_type))));
2323 /* collect the subtype for common-supertype choice */
2324 anycompatible_actual_types[n_anycompatible_args++] = anycompatible_range_typelem;
2325 }
2326 }
2327 else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
2328 {
2329 have_poly_anycompatible = true;
2330 have_anycompatible_multirange = true;
2331 if (actual_type == UNKNOWNOID)
2332 continue;
2333 if (allow_poly && decl_type == actual_type)
2334 continue; /* no new information here */
2335 actual_type = getBaseType(actual_type); /* flatten domains */
2336 if (OidIsValid(anycompatible_multirange_typeid))
2337 {
2338 /* All ANYCOMPATIBLEMULTIRANGE arguments must be the same type */
2339 if (anycompatible_multirange_typeid != actual_type)
2340 ereport(ERROR,
2341 (errcode(ERRCODE_DATATYPE_MISMATCH),
2342 errmsg("arguments declared \"%s\" are not all alike", "anycompatiblemultirange"),
2343 errdetail("%s versus %s",
2344 format_type_be(anycompatible_multirange_typeid),
2345 format_type_be(actual_type))));
2346 }
2347 else
2348 {
2349 anycompatible_multirange_typeid = actual_type;
2350 anycompatible_multirange_typelem = get_multirange_range(actual_type);
2351 if (!OidIsValid(anycompatible_multirange_typelem))
2352 ereport(ERROR,
2353 (errcode(ERRCODE_DATATYPE_MISMATCH),
2354 errmsg("argument declared %s is not a multirange type but type %s",
2355 "anycompatiblemultirange",
2356 format_type_be(actual_type))));
2357 /* we'll consider the subtype below */
2358 }
2359 }
2360 }
2361
2362 /*
2363 * Fast Track: if none of the arguments are polymorphic, return the
2364 * unmodified rettype. Not our job to resolve it if it's polymorphic.
2365 */
2366 if (n_poly_args == 0 && !have_poly_anycompatible)
2367 return rettype;
2368
2369 /* Check matching of family-1 polymorphic arguments, if any */
2370 if (n_poly_args)
2371 {
2372 /* Get the element type based on the array type, if we have one */
2373 if (OidIsValid(array_typeid))
2374 {
2375 Oid array_typelem;
2376
2377 if (array_typeid == ANYARRAYOID)
2378 {
2379 /*
2380 * Special case for matching ANYARRAY input to an ANYARRAY
2381 * argument: allow it iff no other arguments are family-1
2382 * polymorphics (otherwise we couldn't be sure whether the
2383 * array element type matches up) and the result type doesn't
2384 * require us to infer a specific element type.
2385 */
2386 if (n_poly_args != 1 ||
2387 (rettype != ANYARRAYOID &&
2388 IsPolymorphicTypeFamily1(rettype)))
2389 ereport(ERROR,
2390 (errcode(ERRCODE_DATATYPE_MISMATCH),
2391 errmsg("cannot determine element type of \"anyarray\" argument")));
2392 array_typelem = ANYELEMENTOID;
2393 }
2394 else
2395 {
2396 array_typelem = get_element_type(array_typeid);
2397 if (!OidIsValid(array_typelem))
2398 ereport(ERROR,
2399 (errcode(ERRCODE_DATATYPE_MISMATCH),
2400 errmsg("argument declared %s is not an array but type %s",
2401 "anyarray", format_type_be(array_typeid))));
2402 }
2403
2404 if (!OidIsValid(elem_typeid))
2405 {
2406 /*
2407 * if we don't have an element type yet, use the one we just
2408 * got
2409 */
2410 elem_typeid = array_typelem;
2411 }
2412 else if (array_typelem != elem_typeid)
2413 {
2414 /* otherwise, they better match */
2415 ereport(ERROR,
2416 (errcode(ERRCODE_DATATYPE_MISMATCH),
2417 errmsg("argument declared %s is not consistent with argument declared %s",
2418 "anyarray", "anyelement"),
2419 errdetail("%s versus %s",
2420 format_type_be(array_typeid),
2421 format_type_be(elem_typeid))));
2422 }
2423 }
2424
2425 /* Deduce range type from multirange type, or vice versa */
2426 if (OidIsValid(multirange_typeid))
2427 {
2428 Oid multirange_typelem;
2429
2430 multirange_typelem = get_multirange_range(multirange_typeid);
2431 if (!OidIsValid(multirange_typelem))
2432 ereport(ERROR,
2433 (errcode(ERRCODE_DATATYPE_MISMATCH),
2434 errmsg("argument declared %s is not a multirange type but type %s",
2435 "anymultirange",
2436 format_type_be(multirange_typeid))));
2437
2438 if (!OidIsValid(range_typeid))
2439 {
2440 /* if we don't have a range type yet, use the one we just got */
2441 range_typeid = multirange_typelem;
2442 }
2443 else if (multirange_typelem != range_typeid)
2444 {
2445 /* otherwise, they better match */
2446 ereport(ERROR,
2447 (errcode(ERRCODE_DATATYPE_MISMATCH),
2448 errmsg("argument declared %s is not consistent with argument declared %s",
2449 "anymultirange", "anyrange"),
2450 errdetail("%s versus %s",
2451 format_type_be(multirange_typeid),
2452 format_type_be(range_typeid))));
2453 }
2454 }
2455 else if (have_anymultirange && OidIsValid(range_typeid))
2456 {
2457 multirange_typeid = get_range_multirange(range_typeid);
2458 /* We'll complain below if that didn't work */
2459 }
2460
2461 /* Get the element type based on the range type, if we have one */
2462 if (OidIsValid(range_typeid))
2463 {
2464 Oid range_typelem;
2465
2466 range_typelem = get_range_subtype(range_typeid);
2467 if (!OidIsValid(range_typelem))
2468 ereport(ERROR,
2469 (errcode(ERRCODE_DATATYPE_MISMATCH),
2470 errmsg("argument declared %s is not a range type but type %s",
2471 "anyrange",
2472 format_type_be(range_typeid))));
2473
2474 if (!OidIsValid(elem_typeid))
2475 {
2476 /*
2477 * if we don't have an element type yet, use the one we just
2478 * got
2479 */
2480 elem_typeid = range_typelem;
2481 }
2482 else if (range_typelem != elem_typeid)
2483 {
2484 /* otherwise, they better match */
2485 ereport(ERROR,
2486 (errcode(ERRCODE_DATATYPE_MISMATCH),
2487 errmsg("argument declared %s is not consistent with argument declared %s",
2488 "anyrange", "anyelement"),
2489 errdetail("%s versus %s",
2490 format_type_be(range_typeid),
2491 format_type_be(elem_typeid))));
2492 }
2493 }
2494
2495 if (!OidIsValid(elem_typeid))
2496 {
2497 if (allow_poly)
2498 {
2499 elem_typeid = ANYELEMENTOID;
2500 array_typeid = ANYARRAYOID;
2501 range_typeid = ANYRANGEOID;
2502 multirange_typeid = ANYMULTIRANGEOID;
2503 }
2504 else
2505 {
2506 /*
2507 * Only way to get here is if all the family-1 polymorphic
2508 * arguments have UNKNOWN inputs.
2509 */
2510 ereport(ERROR,
2511 (errcode(ERRCODE_DATATYPE_MISMATCH),
2512 errmsg("could not determine polymorphic type because input has type %s",
2513 "unknown")));
2514 }
2515 }
2516
2517 if (have_anynonarray && elem_typeid != ANYELEMENTOID)
2518 {
2519 /*
2520 * require the element type to not be an array or domain over
2521 * array
2522 */
2523 if (type_is_array_domain(elem_typeid))
2524 ereport(ERROR,
2525 (errcode(ERRCODE_DATATYPE_MISMATCH),
2526 errmsg("type matched to anynonarray is an array type: %s",
2527 format_type_be(elem_typeid))));
2528 }
2529
2530 if (have_anyenum && elem_typeid != ANYELEMENTOID)
2531 {
2532 /* require the element type to be an enum */
2533 if (!type_is_enum(elem_typeid))
2534 ereport(ERROR,
2535 (errcode(ERRCODE_DATATYPE_MISMATCH),
2536 errmsg("type matched to anyenum is not an enum type: %s",
2537 format_type_be(elem_typeid))));
2538 }
2539 }
2540
2541 /* Check matching of family-2 polymorphic arguments, if any */
2542 if (have_poly_anycompatible)
2543 {
2544 /* Deduce range type from multirange type, or vice versa */
2545 if (OidIsValid(anycompatible_multirange_typeid))
2546 {
2547 if (OidIsValid(anycompatible_range_typeid))
2548 {
2549 if (anycompatible_multirange_typelem !=
2550 anycompatible_range_typeid)
2551 ereport(ERROR,
2552 (errcode(ERRCODE_DATATYPE_MISMATCH),
2553 errmsg("argument declared %s is not consistent with argument declared %s",
2554 "anycompatiblemultirange",
2555 "anycompatiblerange"),
2556 errdetail("%s versus %s",
2557 format_type_be(anycompatible_multirange_typeid),
2558 format_type_be(anycompatible_range_typeid))));
2559 }
2560 else
2561 {
2562 anycompatible_range_typeid = anycompatible_multirange_typelem;
2563 anycompatible_range_typelem = get_range_subtype(anycompatible_range_typeid);
2564 if (!OidIsValid(anycompatible_range_typelem))
2565 ereport(ERROR,
2566 (errcode(ERRCODE_DATATYPE_MISMATCH),
2567 errmsg("argument declared %s is not a multirange type but type %s",
2568 "anycompatiblemultirange",
2569 format_type_be(anycompatible_multirange_typeid))));
2570 /* this enables element type matching check below */
2571 have_anycompatible_range = true;
2572 /* collect the subtype for common-supertype choice */
2573 anycompatible_actual_types[n_anycompatible_args++] =
2574 anycompatible_range_typelem;
2575 }
2576 }
2577 else if (have_anycompatible_multirange &&
2578 OidIsValid(anycompatible_range_typeid))
2579 {
2580 anycompatible_multirange_typeid = get_range_multirange(anycompatible_range_typeid);
2581 /* We'll complain below if that didn't work */
2582 }
2583
2584 if (n_anycompatible_args > 0)
2585 {
2586 anycompatible_typeid =
2587 select_common_type_from_oids(n_anycompatible_args,
2588 anycompatible_actual_types,
2589 false);
2590
2591 /* We have to verify that the selected type actually works */
2592 if (!verify_common_type_from_oids(anycompatible_typeid,
2593 n_anycompatible_args,
2594 anycompatible_actual_types))
2595 ereport(ERROR,
2596 (errcode(ERRCODE_DATATYPE_MISMATCH),
2597 errmsg("arguments of anycompatible family cannot be cast to a common type")));
2598
2599 if (have_anycompatible_array)
2600 {
2601 anycompatible_array_typeid = get_array_type(anycompatible_typeid);
2602 if (!OidIsValid(anycompatible_array_typeid))
2603 ereport(ERROR,
2604 (errcode(ERRCODE_UNDEFINED_OBJECT),
2605 errmsg("could not find array type for data type %s",
2606 format_type_be(anycompatible_typeid))));
2607 }
2608
2609 if (have_anycompatible_range)
2610 {
2611 /* we can't infer a range type from the others */
2612 if (!OidIsValid(anycompatible_range_typeid))
2613 ereport(ERROR,
2614 (errcode(ERRCODE_DATATYPE_MISMATCH),
2615 errmsg("could not determine polymorphic type %s because input has type %s",
2616 "anycompatiblerange", "unknown")));
2617
2618 /*
2619 * the anycompatible type must exactly match the range element
2620 * type
2621 */
2622 if (anycompatible_range_typelem != anycompatible_typeid)
2623 ereport(ERROR,
2624 (errcode(ERRCODE_DATATYPE_MISMATCH),
2625 errmsg("anycompatiblerange type %s does not match anycompatible type %s",
2626 format_type_be(anycompatible_range_typeid),
2627 format_type_be(anycompatible_typeid))));
2628 }
2629
2630 if (have_anycompatible_multirange)
2631 {
2632 /* we can't infer a multirange type from the others */
2633 if (!OidIsValid(anycompatible_multirange_typeid))
2634 ereport(ERROR,
2635 (errcode(ERRCODE_DATATYPE_MISMATCH),
2636 errmsg("could not determine polymorphic type %s because input has type %s",
2637 "anycompatiblemultirange", "unknown")));
2638
2639 /*
2640 * the anycompatible type must exactly match the multirange
2641 * element type
2642 */
2643 if (anycompatible_range_typelem != anycompatible_typeid)
2644 ereport(ERROR,
2645 (errcode(ERRCODE_DATATYPE_MISMATCH),
2646 errmsg("anycompatiblemultirange type %s does not match anycompatible type %s",
2647 format_type_be(anycompatible_multirange_typeid),
2648 format_type_be(anycompatible_typeid))));
2649 }
2650
2651 if (have_anycompatible_nonarray)
2652 {
2653 /*
2654 * require the element type to not be an array or domain over
2655 * array
2656 */
2657 if (type_is_array_domain(anycompatible_typeid))
2658 ereport(ERROR,
2659 (errcode(ERRCODE_DATATYPE_MISMATCH),
2660 errmsg("type matched to anycompatiblenonarray is an array type: %s",
2661 format_type_be(anycompatible_typeid))));
2662 }
2663 }
2664 else
2665 {
2666 if (allow_poly)
2667 {
2668 anycompatible_typeid = ANYCOMPATIBLEOID;
2669 anycompatible_array_typeid = ANYCOMPATIBLEARRAYOID;
2670 anycompatible_range_typeid = ANYCOMPATIBLERANGEOID;
2671 anycompatible_multirange_typeid = ANYCOMPATIBLEMULTIRANGEOID;
2672 }
2673 else
2674 {
2675 /*
2676 * Only way to get here is if all the family-2 polymorphic
2677 * arguments have UNKNOWN inputs. Resolve to TEXT as
2678 * select_common_type() would do. That doesn't license us to
2679 * use TEXTRANGE or TEXTMULTIRANGE, though.
2680 */
2681 anycompatible_typeid = TEXTOID;
2682 anycompatible_array_typeid = TEXTARRAYOID;
2683 if (have_anycompatible_range)
2684 ereport(ERROR,
2685 (errcode(ERRCODE_DATATYPE_MISMATCH),
2686 errmsg("could not determine polymorphic type %s because input has type %s",
2687 "anycompatiblerange", "unknown")));
2688 if (have_anycompatible_multirange)
2689 ereport(ERROR,
2690 (errcode(ERRCODE_DATATYPE_MISMATCH),
2691 errmsg("could not determine polymorphic type %s because input has type %s",
2692 "anycompatiblemultirange", "unknown")));
2693 }
2694 }
2695
2696 /* replace family-2 polymorphic types by selected types */
2697 for (int j = 0; j < nargs; j++)
2698 {
2699 Oid decl_type = declared_arg_types[j];
2700
2701 if (decl_type == ANYCOMPATIBLEOID ||
2702 decl_type == ANYCOMPATIBLENONARRAYOID)
2703 declared_arg_types[j] = anycompatible_typeid;
2704 else if (decl_type == ANYCOMPATIBLEARRAYOID)
2705 declared_arg_types[j] = anycompatible_array_typeid;
2706 else if (decl_type == ANYCOMPATIBLERANGEOID)
2707 declared_arg_types[j] = anycompatible_range_typeid;
2708 else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
2709 declared_arg_types[j] = anycompatible_multirange_typeid;
2710 }
2711 }
2712
2713 /*
2714 * If we had any UNKNOWN inputs for family-1 polymorphic arguments,
2715 * re-scan to assign correct types to them.
2716 *
2717 * Note: we don't have to consider unknown inputs that were matched to
2718 * family-2 polymorphic arguments, because we forcibly updated their
2719 * declared_arg_types[] positions just above.
2720 */
2721 if (have_poly_unknowns)
2722 {
2723 for (int j = 0; j < nargs; j++)
2724 {
2725 Oid decl_type = declared_arg_types[j];
2726 Oid actual_type = actual_arg_types[j];
2727
2728 if (actual_type != UNKNOWNOID)
2729 continue;
2730
2731 if (decl_type == ANYELEMENTOID ||
2732 decl_type == ANYNONARRAYOID ||
2733 decl_type == ANYENUMOID)
2734 declared_arg_types[j] = elem_typeid;
2735 else if (decl_type == ANYARRAYOID)
2736 {
2737 if (!OidIsValid(array_typeid))
2738 {
2739 array_typeid = get_array_type(elem_typeid);
2740 if (!OidIsValid(array_typeid))
2741 ereport(ERROR,
2742 (errcode(ERRCODE_UNDEFINED_OBJECT),
2743 errmsg("could not find array type for data type %s",
2744 format_type_be(elem_typeid))));
2745 }
2746 declared_arg_types[j] = array_typeid;
2747 }
2748 else if (decl_type == ANYRANGEOID)
2749 {
2750 if (!OidIsValid(range_typeid))
2751 {
2752 /* we can't infer a range type from the others */
2753 ereport(ERROR,
2754 (errcode(ERRCODE_DATATYPE_MISMATCH),
2755 errmsg("could not determine polymorphic type %s because input has type %s",
2756 "anyrange", "unknown")));
2757 }
2758 declared_arg_types[j] = range_typeid;
2759 }
2760 else if (decl_type == ANYMULTIRANGEOID)
2761 {
2762 if (!OidIsValid(multirange_typeid))
2763 {
2764 /* we can't infer a multirange type from the others */
2765 ereport(ERROR,
2766 (errcode(ERRCODE_DATATYPE_MISMATCH),
2767 errmsg("could not determine polymorphic type %s because input has type %s",
2768 "anymultirange", "unknown")));
2769 }
2770 declared_arg_types[j] = multirange_typeid;
2771 }
2772 }
2773 }
2774
2775 /* if we return ANYELEMENT use the appropriate argument type */
2776 if (rettype == ANYELEMENTOID ||
2777 rettype == ANYNONARRAYOID ||
2778 rettype == ANYENUMOID)
2779 return elem_typeid;
2780
2781 /* if we return ANYARRAY use the appropriate argument type */
2782 if (rettype == ANYARRAYOID)
2783 {
2784 if (!OidIsValid(array_typeid))
2785 {
2786 array_typeid = get_array_type(elem_typeid);
2787 if (!OidIsValid(array_typeid))
2788 ereport(ERROR,
2789 (errcode(ERRCODE_UNDEFINED_OBJECT),
2790 errmsg("could not find array type for data type %s",
2791 format_type_be(elem_typeid))));
2792 }
2793 return array_typeid;
2794 }
2795
2796 /* if we return ANYRANGE use the appropriate argument type */
2797 if (rettype == ANYRANGEOID)
2798 {
2799 /* this error is unreachable if the function signature is valid: */
2800 if (!OidIsValid(range_typeid))
2801 ereport(ERROR,
2802 (errcode(ERRCODE_DATATYPE_MISMATCH),
2803 errmsg_internal("could not determine polymorphic type %s because input has type %s",
2804 "anyrange", "unknown")));
2805 return range_typeid;
2806 }
2807
2808 /* if we return ANYMULTIRANGE use the appropriate argument type */
2809 if (rettype == ANYMULTIRANGEOID)
2810 {
2811 /* this error is unreachable if the function signature is valid: */
2812 if (!OidIsValid(multirange_typeid))
2813 ereport(ERROR,
2814 (errcode(ERRCODE_DATATYPE_MISMATCH),
2815 errmsg_internal("could not determine polymorphic type %s because input has type %s",
2816 "anymultirange", "unknown")));
2817 return multirange_typeid;
2818 }
2819
2820 /* if we return ANYCOMPATIBLE use the appropriate type */
2821 if (rettype == ANYCOMPATIBLEOID ||
2822 rettype == ANYCOMPATIBLENONARRAYOID)
2823 {
2824 /* this error is unreachable if the function signature is valid: */
2825 if (!OidIsValid(anycompatible_typeid))
2826 ereport(ERROR,
2827 (errcode(ERRCODE_DATATYPE_MISMATCH),
2828 errmsg_internal("could not identify anycompatible type")));
2829 return anycompatible_typeid;
2830 }
2831
2832 /* if we return ANYCOMPATIBLEARRAY use the appropriate type */
2833 if (rettype == ANYCOMPATIBLEARRAYOID)
2834 {
2835 /* this error is unreachable if the function signature is valid: */
2836 if (!OidIsValid(anycompatible_array_typeid))
2837 ereport(ERROR,
2838 (errcode(ERRCODE_DATATYPE_MISMATCH),
2839 errmsg_internal("could not identify anycompatiblearray type")));
2840 return anycompatible_array_typeid;
2841 }
2842
2843 /* if we return ANYCOMPATIBLERANGE use the appropriate argument type */
2844 if (rettype == ANYCOMPATIBLERANGEOID)
2845 {
2846 /* this error is unreachable if the function signature is valid: */
2847 if (!OidIsValid(anycompatible_range_typeid))
2848 ereport(ERROR,
2849 (errcode(ERRCODE_DATATYPE_MISMATCH),
2850 errmsg_internal("could not identify anycompatiblerange type")));
2851 return anycompatible_range_typeid;
2852 }
2853
2854 /* if we return ANYCOMPATIBLEMULTIRANGE use the appropriate argument type */
2855 if (rettype == ANYCOMPATIBLEMULTIRANGEOID)
2856 {
2857 /* this error is unreachable if the function signature is valid: */
2858 if (!OidIsValid(anycompatible_multirange_typeid))
2859 ereport(ERROR,
2860 (errcode(ERRCODE_DATATYPE_MISMATCH),
2861 errmsg_internal("could not identify anycompatiblemultirange type")));
2862 return anycompatible_multirange_typeid;
2863 }
2864
2865 /* we don't return a generic type; send back the original return type */
2866 return rettype;
2867 }
2868
2869 /*
2870 * check_valid_polymorphic_signature()
2871 * Is a proposed function signature valid per polymorphism rules?
2872 *
2873 * Returns NULL if the signature is valid (either ret_type is not polymorphic,
2874 * or it can be deduced from the given declared argument types). Otherwise,
2875 * returns a palloc'd, already translated errdetail string saying why not.
2876 */
2877 char *
2878 check_valid_polymorphic_signature(Oid ret_type,
2879 const Oid *declared_arg_types,
2880 int nargs)
2881 {
2882 if (ret_type == ANYRANGEOID || ret_type == ANYMULTIRANGEOID)
2883 {
2884 /*
2885 * ANYRANGE and ANYMULTIRANGE require an ANYRANGE or ANYMULTIRANGE
2886 * input, else we can't tell which of several range types with the
2887 * same element type to use.
2888 */
2889 for (int i = 0; i < nargs; i++)
2890 {
2891 if (declared_arg_types[i] == ANYRANGEOID ||
2892 declared_arg_types[i] == ANYMULTIRANGEOID)
2893 return NULL; /* OK */
2894 }
2895 return psprintf(_("A result of type %s requires at least one input of type anyrange or anymultirange."),
2896 format_type_be(ret_type));
2897 }
2898 else if (ret_type == ANYCOMPATIBLERANGEOID || ret_type == ANYCOMPATIBLEMULTIRANGEOID)
2899 {
2900 /*
2901 * ANYCOMPATIBLERANGE and ANYCOMPATIBLEMULTIRANGE require an
2902 * ANYCOMPATIBLERANGE or ANYCOMPATIBLEMULTIRANGE input, else we can't
2903 * tell which of several range types with the same element type to
2904 * use.
2905 */
2906 for (int i = 0; i < nargs; i++)
2907 {
2908 if (declared_arg_types[i] == ANYCOMPATIBLERANGEOID ||
2909 declared_arg_types[i] == ANYCOMPATIBLEMULTIRANGEOID)
2910 return NULL; /* OK */
2911 }
2912 return psprintf(_("A result of type %s requires at least one input of type anycompatiblerange or anycompatiblemultirange."),
2913 format_type_be(ret_type));
2914 }
2915 else if (IsPolymorphicTypeFamily1(ret_type))
2916 {
2917 /* Otherwise, any family-1 type can be deduced from any other */
2918 for (int i = 0; i < nargs; i++)
2919 {
2920 if (IsPolymorphicTypeFamily1(declared_arg_types[i]))
2921 return NULL; /* OK */
2922 }
2923 /* Keep this list in sync with IsPolymorphicTypeFamily1! */
2924 return psprintf(_("A result of type %s requires at least one input of type anyelement, anyarray, anynonarray, anyenum, anyrange, or anymultirange."),
2925 format_type_be(ret_type));
2926 }
2927 else if (IsPolymorphicTypeFamily2(ret_type))
2928 {
2929 /* Otherwise, any family-2 type can be deduced from any other */
2930 for (int i = 0; i < nargs; i++)
2931 {
2932 if (IsPolymorphicTypeFamily2(declared_arg_types[i]))
2933 return NULL; /* OK */
2934 }
2935 /* Keep this list in sync with IsPolymorphicTypeFamily2! */
2936 return psprintf(_("A result of type %s requires at least one input of type anycompatible, anycompatiblearray, anycompatiblenonarray, anycompatiblerange, or anycompatiblemultirange."),
2937 format_type_be(ret_type));
2938 }
2939 else
2940 return NULL; /* OK, ret_type is not polymorphic */
2941 }
2942
2943 /*
2944 * check_valid_internal_signature()
2945 * Is a proposed function signature valid per INTERNAL safety rules?
2946 *
2947 * Returns NULL if OK, or a suitable error message if ret_type is INTERNAL but
2948 * none of the declared arg types are. (It's unsafe to create such a function
2949 * since it would allow invocation of INTERNAL-consuming functions directly
2950 * from SQL.) It's overkill to return the error detail message, since there
2951 * is only one possibility, but we do it like this to keep the API similar to
2952 * check_valid_polymorphic_signature().
2953 */
2954 char *
2955 check_valid_internal_signature(Oid ret_type,
2956 const Oid *declared_arg_types,
2957 int nargs)
2958 {
2959 if (ret_type == INTERNALOID)
2960 {
2961 for (int i = 0; i < nargs; i++)
2962 {
2963 if (declared_arg_types[i] == ret_type)
2964 return NULL; /* OK */
2965 }
2966 return pstrdup(_("A result of type internal requires at least one input of type internal."));
2967 }
2968 else
2969 return NULL; /* OK, ret_type is not INTERNAL */
2970 }
2971
2972
2973 /* TypeCategory()
2974 * Assign a category to the specified type OID.
2975 *
2976 * NB: this must not return TYPCATEGORY_INVALID.
2977 */
2978 TYPCATEGORY
2979 TypeCategory(Oid type)
2980 {
2981 char typcategory;
2982 bool typispreferred;
2983
2984 get_type_category_preferred(type, &typcategory, &typispreferred);
2985 Assert(typcategory != TYPCATEGORY_INVALID);
2986 return (TYPCATEGORY) typcategory;
2987 }
2988
2989
2990 /* IsPreferredType()
2991 * Check if this type is a preferred type for the given category.
2992 *
2993 * If category is TYPCATEGORY_INVALID, then we'll return true for preferred
2994 * types of any category; otherwise, only for preferred types of that
2995 * category.
2996 */
2997 bool
2998 IsPreferredType(TYPCATEGORY category, Oid type)
2999 {
3000 char typcategory;
3001 bool typispreferred;
3002
3003 get_type_category_preferred(type, &typcategory, &typispreferred);
3004 if (category == typcategory || category == TYPCATEGORY_INVALID)
3005 return typispreferred;
3006 else
3007 return false;
3008 }
3009
3010
3011 /* IsBinaryCoercible()
3012 * Check if srctype is binary-coercible to targettype.
3013 *
3014 * This notion allows us to cheat and directly exchange values without
3015 * going through the trouble of calling a conversion function. Note that
3016 * in general, this should only be an implementation shortcut. Before 7.4,
3017 * this was also used as a heuristic for resolving overloaded functions and
3018 * operators, but that's basically a bad idea.
3019 *
3020 * As of 7.3, binary coercibility isn't hardwired into the code anymore.
3021 * We consider two types binary-coercible if there is an implicitly
3022 * invokable, no-function-needed pg_cast entry. Also, a domain is always
3023 * binary-coercible to its base type, though *not* vice versa (in the other
3024 * direction, one must apply domain constraint checks before accepting the
3025 * value as legitimate). We also need to special-case various polymorphic
3026 * types.
3027 *
3028 * This function replaces IsBinaryCompatible(), which was an inherently
3029 * symmetric test. Since the pg_cast entries aren't necessarily symmetric,
3030 * the order of the operands is now significant.
3031 */
3032 bool
3033 IsBinaryCoercible(Oid srctype, Oid targettype)
3034 {
3035 Oid castoid;
3036
3037 return IsBinaryCoercibleWithCast(srctype, targettype, &castoid);
3038 }
3039
3040 /* IsBinaryCoercibleWithCast()
3041 * Check if srctype is binary-coercible to targettype.
3042 *
3043 * This variant also returns the OID of the pg_cast entry if one is involved.
3044 * *castoid is set to InvalidOid if no binary-coercible cast exists, or if
3045 * there is a hard-wired rule for it rather than a pg_cast entry.
3046 */
3047 bool
3048 IsBinaryCoercibleWithCast(Oid srctype, Oid targettype,
3049 Oid *castoid)
3050 {
3051 HeapTuple tuple;
3052 Form_pg_cast castForm;
3053 bool result;
3054
3055 *castoid = InvalidOid;
3056
3057 /* Fast path if same type */
3058 if (srctype == targettype)
3059 return true;
3060
3061 /* Anything is coercible to ANY or ANYELEMENT or ANYCOMPATIBLE */
3062 if (targettype == ANYOID || targettype == ANYELEMENTOID ||
3063 targettype == ANYCOMPATIBLEOID)
3064 return true;
3065
3066 /* If srctype is a domain, reduce to its base type */
3067 if (OidIsValid(srctype))
3068 srctype = getBaseType(srctype);
3069
3070 /* Somewhat-fast path for domain -> base type case */
3071 if (srctype == targettype)
3072 return true;
3073
3074 /* Also accept any array type as coercible to ANY[COMPATIBLE]ARRAY */
3075 if (targettype == ANYARRAYOID || targettype == ANYCOMPATIBLEARRAYOID)
3076 if (type_is_array(srctype))
3077 return true;
3078
3079 /* Also accept any non-array type as coercible to ANY[COMPATIBLE]NONARRAY */
3080 if (targettype == ANYNONARRAYOID || targettype == ANYCOMPATIBLENONARRAYOID)
3081 if (!type_is_array(srctype))
3082 return true;
3083
3084 /* Also accept any enum type as coercible to ANYENUM */
3085 if (targettype == ANYENUMOID)
3086 if (type_is_enum(srctype))
3087 return true;
3088
3089 /* Also accept any range type as coercible to ANY[COMPATIBLE]RANGE */
3090 if (targettype == ANYRANGEOID || targettype == ANYCOMPATIBLERANGEOID)
3091 if (type_is_range(srctype))
3092 return true;
3093
3094 /* Also, any multirange type is coercible to ANY[COMPATIBLE]MULTIRANGE */
3095 if (targettype == ANYMULTIRANGEOID || targettype == ANYCOMPATIBLEMULTIRANGEOID)
3096 if (type_is_multirange(srctype))
3097 return true;
3098
3099 /* Also accept any composite type as coercible to RECORD */
3100 if (targettype == RECORDOID)
3101 if (ISCOMPLEX(srctype))
3102 return true;
3103
3104 /* Also accept any composite array type as coercible to RECORD[] */
3105 if (targettype == RECORDARRAYOID)
3106 if (is_complex_array(srctype))
3107 return true;
3108
3109 /* Else look in pg_cast */
3110 tuple = SearchSysCache2(CASTSOURCETARGET,
3111 ObjectIdGetDatum(srctype),
3112 ObjectIdGetDatum(targettype));
3113 if (!HeapTupleIsValid(tuple))
3114 return false; /* no cast */
3115 castForm = (Form_pg_cast) GETSTRUCT(tuple);
3116
3117 result = (castForm->castmethod == COERCION_METHOD_BINARY &&
3118 castForm->castcontext == COERCION_CODE_IMPLICIT);
3119
3120 if (result)
3121 *castoid = castForm->oid;
3122
3123 ReleaseSysCache(tuple);
3124
3125 return result;
3126 }
3127
3128
3129 /*
3130 * find_coercion_pathway
3131 * Look for a coercion pathway between two types.
3132 *
3133 * Currently, this deals only with scalar-type cases; it does not consider
3134 * polymorphic types nor casts between composite types. (Perhaps fold
3135 * those in someday?)
3136 *
3137 * ccontext determines the set of available casts.
3138 *
3139 * The possible result codes are:
3140 * COERCION_PATH_NONE: failed to find any coercion pathway
3141 * *funcid is set to InvalidOid
3142 * COERCION_PATH_FUNC: apply the coercion function returned in *funcid
3143 * COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
3144 * *funcid is set to InvalidOid
3145 * COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
3146 * *funcid is set to InvalidOid
3147 * COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
3148 * *funcid is set to InvalidOid
3149 *
3150 * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
3151 * needed to do the coercion; if the target is a domain then we may need to
3152 * apply domain constraint checking. If you want to check for a zero-effort
3153 * conversion then use IsBinaryCoercible().
3154 */
3155 CoercionPathType
3156 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
3157 CoercionContext ccontext,
3158 Oid *funcid)
3159 {
3160 CoercionPathType result = COERCION_PATH_NONE;
3161 HeapTuple tuple;
3162
3163 *funcid = InvalidOid;
3164
3165 /* Perhaps the types are domains; if so, look at their base types */
3166 if (OidIsValid(sourceTypeId))
3167 sourceTypeId = getBaseType(sourceTypeId);
3168 if (OidIsValid(targetTypeId))
3169 targetTypeId = getBaseType(targetTypeId);
3170
3171 /* Domains are always coercible to and from their base type */
3172 if (sourceTypeId == targetTypeId)
3173 return COERCION_PATH_RELABELTYPE;
3174
3175 /* Reject all cases of casting something else to/from "internal" */
3176 if (sourceTypeId == INTERNALOID || targetTypeId == INTERNALOID)
3177 return COERCION_PATH_NONE;
3178
3179 /* Look in pg_cast */
3180 tuple = SearchSysCache2(CASTSOURCETARGET,
3181 ObjectIdGetDatum(sourceTypeId),
3182 ObjectIdGetDatum(targetTypeId));
3183
3184 if (HeapTupleIsValid(tuple))
3185 {
3186 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
3187 CoercionContext castcontext;
3188
3189 /* convert char value for castcontext to CoercionContext enum */
3190 switch (castForm->castcontext)
3191 {
3192 case COERCION_CODE_IMPLICIT:
3193 castcontext = COERCION_IMPLICIT;
3194 break;
3195 case COERCION_CODE_ASSIGNMENT:
3196 castcontext = COERCION_ASSIGNMENT;
3197 break;
3198 case COERCION_CODE_EXPLICIT:
3199 castcontext = COERCION_EXPLICIT;
3200 break;
3201 default:
3202 elog(ERROR, "unrecognized castcontext: %d",
3203 (int) castForm->castcontext);
3204 castcontext = 0; /* keep compiler quiet */
3205 break;
3206 }
3207
3208 /* Rely on ordering of enum for correct behavior here */
3209 if (ccontext >= castcontext)
3210 {
3211 switch (castForm->castmethod)
3212 {
3213 case COERCION_METHOD_FUNCTION:
3214 result = COERCION_PATH_FUNC;
3215 *funcid = castForm->castfunc;
3216 break;
3217 case COERCION_METHOD_INOUT:
3218 result = COERCION_PATH_COERCEVIAIO;
3219 break;
3220 case COERCION_METHOD_BINARY:
3221 result = COERCION_PATH_RELABELTYPE;
3222 break;
3223 default:
3224 elog(ERROR, "unrecognized castmethod: %d",
3225 (int) castForm->castmethod);
3226 break;
3227 }
3228 }
3229
3230 ReleaseSysCache(tuple);
3231 }
3232 else
3233 {
3234 /*
3235 * If there's no pg_cast entry, perhaps we are dealing with a pair of
3236 * array types. If so, and if their element types have a conversion
3237 * pathway, report that we can coerce with an ArrayCoerceExpr.
3238 *
3239 * Hack: disallow coercions to oidvector and int2vector, which
3240 * otherwise tend to capture coercions that should go to "real" array
3241 * types. We want those types to be considered "real" arrays for many
3242 * purposes, but not this one. (Also, ArrayCoerceExpr isn't
3243 * guaranteed to produce an output that meets the restrictions of
3244 * these datatypes, such as being 1-dimensional.)
3245 */
3246 if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
3247 {
3248 Oid targetElem;
3249 Oid sourceElem;
3250
3251 if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
3252 (sourceElem = get_element_type(sourceTypeId)) != InvalidOid)
3253 {
3254 CoercionPathType elempathtype;
3255 Oid elemfuncid;
3256
3257 elempathtype = find_coercion_pathway(targetElem,
3258 sourceElem,
3259 ccontext,
3260 &elemfuncid);
3261 if (elempathtype != COERCION_PATH_NONE)
3262 {
3263 result = COERCION_PATH_ARRAYCOERCE;
3264 }
3265 }
3266 }
3267
3268 /*
3269 * If we still haven't found a possibility, consider automatic casting
3270 * using I/O functions. We allow assignment casts to string types and
3271 * explicit casts from string types to be handled this way. (The
3272 * CoerceViaIO mechanism is a lot more general than that, but this is
3273 * all we want to allow in the absence of a pg_cast entry.) It would
3274 * probably be better to insist on explicit casts in both directions,
3275 * but this is a compromise to preserve something of the pre-8.3
3276 * behavior that many types had implicit (yipes!) casts to text.
3277 */
3278 if (result == COERCION_PATH_NONE)
3279 {
3280 if (ccontext >= COERCION_ASSIGNMENT &&
3281 TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
3282 result = COERCION_PATH_COERCEVIAIO;
3283 else if (ccontext >= COERCION_EXPLICIT &&
3284 TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
3285 result = COERCION_PATH_COERCEVIAIO;
3286 }
3287 }
3288
3289 /*
3290 * When parsing PL/pgSQL assignments, allow an I/O cast to be used
3291 * whenever no normal coercion is available.
3292 */
3293 if (result == COERCION_PATH_NONE &&
3294 ccontext == COERCION_PLPGSQL)
3295 result = COERCION_PATH_COERCEVIAIO;
3296
3297 return result;
3298 }
3299
3300
3301 /*
3302 * find_typmod_coercion_function -- does the given type need length coercion?
3303 *
3304 * If the target type possesses a pg_cast function from itself to itself,
3305 * it must need length coercion.
3306 *
3307 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
3308 *
3309 * If the given type is a varlena array type, we do not look for a coercion
3310 * function associated directly with the array type, but instead look for
3311 * one associated with the element type. An ArrayCoerceExpr node must be
3312 * used to apply such a function. (Note: currently, it's pointless to
3313 * return the funcid in this case, because it'll just get looked up again
3314 * in the recursive construction of the ArrayCoerceExpr's elemexpr.)
3315 *
3316 * We use the same result enum as find_coercion_pathway, but the only possible
3317 * result codes are:
3318 * COERCION_PATH_NONE: no length coercion needed
3319 * COERCION_PATH_FUNC: apply the function returned in *funcid
3320 * COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
3321 */
3322 CoercionPathType
3323 find_typmod_coercion_function(Oid typeId,
3324 Oid *funcid)
3325 {
3326 CoercionPathType result;
3327 Type targetType;
3328 Form_pg_type typeForm;
3329 HeapTuple tuple;
3330
3331 *funcid = InvalidOid;
3332 result = COERCION_PATH_FUNC;
3333
3334 targetType = typeidType(typeId);
3335 typeForm = (Form_pg_type) GETSTRUCT(targetType);
3336
3337 /* Check for a "true" array type */
3338 if (IsTrueArrayType(typeForm))
3339 {
3340 /* Yes, switch our attention to the element type */
3341 typeId = typeForm->typelem;
3342 result = COERCION_PATH_ARRAYCOERCE;
3343 }
3344 ReleaseSysCache(targetType);
3345
3346 /* Look in pg_cast */
3347 tuple = SearchSysCache2(CASTSOURCETARGET,
3348 ObjectIdGetDatum(typeId),
3349 ObjectIdGetDatum(typeId));
3350
3351 if (HeapTupleIsValid(tuple))
3352 {
3353 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
3354
3355 *funcid = castForm->castfunc;
3356 ReleaseSysCache(tuple);
3357 }
3358
3359 if (!OidIsValid(*funcid))
3360 result = COERCION_PATH_NONE;
3361
3362 return result;
3363 }
3364
3365 /*
3366 * is_complex_array
3367 * Is this type an array of composite?
3368 *
3369 * Note: this will not return true for record[]; check for RECORDARRAYOID
3370 * separately if needed.
3371 */
3372 static bool
3373 is_complex_array(Oid typid)
3374 {
3375 Oid elemtype = get_element_type(typid);
3376
3377 return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));
3378 }
3379
3380
3381 /*
3382 * Check whether reltypeId is the row type of a typed table of type
3383 * reloftypeId, or is a domain over such a row type. (This is conceptually
3384 * similar to the subtype relationship checked by typeInheritsFrom().)
3385 */
3386 static bool
3387 typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
3388 {
3389 Oid relid = typeOrDomainTypeRelid(reltypeId);
3390 bool result = false;
3391
3392 if (relid)
3393 {
3394 HeapTuple tp;
3395 Form_pg_class reltup;
3396
3397 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
3398 if (!HeapTupleIsValid(tp))
3399 elog(ERROR, "cache lookup failed for relation %u", relid);
3400
3401 reltup = (Form_pg_class) GETSTRUCT(tp);
3402 if (reltup->reloftype == reloftypeId)
3403 result = true;
3404
3405 ReleaseSysCache(tp);
3406 }
3407
3408 return result;
3409 }