1 /*-------------------------------------------------------------------------
4 * handle type coercions/conversions for parser
6 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/parser/parse_coerce.c
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_cast.h"
18 #include "catalog/pg_class.h"
19 #include "catalog/pg_inherits_fn.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/lsyscache.h"
29 #include "utils/syscache.h"
30 #include "utils/typcache.h"
33 static Node *coerce_type_typmod(Node *node,
34 Oid targetTypeId, int32 targetTypMod,
35 CoercionForm cformat, int location,
36 bool isExplicit, bool hideInputCoercion);
37 static void hide_coercion_node(Node *node);
38 static Node *build_coercion_expression(Node *node,
39 CoercionPathType pathtype,
41 Oid targetTypeId, int32 targetTypMod,
42 CoercionForm cformat, int location,
44 static Node *coerce_record_to_complex(ParseState *pstate, Node *node,
46 CoercionContext ccontext,
49 static bool is_complex_array(Oid typid);
50 static bool typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId);
54 * coerce_to_target_type()
55 * Convert an expression to a target type and typmod.
57 * This is the general-purpose entry point for arbitrary type coercion
58 * operations. Direct use of the component operations can_coerce_type,
59 * coerce_type, and coerce_type_typmod should be restricted to special
60 * cases (eg, when the conversion is expected to succeed).
62 * Returns the possibly-transformed expression tree, or NULL if the type
63 * conversion is not possible. (We do this, rather than ereport'ing directly,
64 * so that callers can generate custom error messages indicating context.)
66 * pstate - parse state (can be NULL, see coerce_type)
67 * expr - input expression tree (already transformed by transformExpr)
68 * exprtype - result type of expr
69 * targettype - desired result type
70 * targettypmod - desired result typmod
71 * ccontext, cformat - context indicators to control coercions
72 * location - parse location of the coercion request, or -1 if unknown/implicit
75 coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype,
76 Oid targettype, int32 targettypmod,
77 CoercionContext ccontext,
84 if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
88 * If the input has a CollateExpr at the top, strip it off, perform the
89 * coercion, and put a new one back on. This is annoying since it
90 * duplicates logic in coerce_type, but if we don't do this then it's too
91 * hard to tell whether coerce_type actually changed anything, and we
92 * *must* know that to avoid possibly calling hide_coercion_node on
93 * something that wasn't generated by coerce_type. Note that if there are
94 * multiple stacked CollateExprs, we just discard all but the topmost.
97 while (expr && IsA(expr, CollateExpr))
98 expr = (Node *) ((CollateExpr *) expr)->arg;
100 result = coerce_type(pstate, expr, exprtype,
101 targettype, targettypmod,
102 ccontext, cformat, location);
105 * If the target is a fixed-length type, it may need a length coercion as
106 * well as a type coercion. If we find ourselves adding both, force the
107 * inner coercion node to implicit display form.
109 result = coerce_type_typmod(result,
110 targettype, targettypmod,
112 (cformat != COERCE_IMPLICIT_CAST),
113 (result != expr && !IsA(result, Const)));
115 if (expr != origexpr)
117 /* Reinstall top CollateExpr */
118 CollateExpr *coll = (CollateExpr *) origexpr;
119 CollateExpr *newcoll = makeNode(CollateExpr);
121 newcoll->arg = (Expr *) result;
122 newcoll->collOid = coll->collOid;
123 newcoll->location = coll->location;
124 result = (Node *) newcoll;
133 * Convert an expression to a different type.
135 * The caller should already have determined that the coercion is possible;
136 * see can_coerce_type.
138 * Normally, no coercion to a typmod (length) is performed here. The caller
139 * must call coerce_type_typmod as well, if a typmod constraint is wanted.
140 * (But if the target type is a domain, it may internally contain a
141 * typmod constraint, which will be applied inside coerce_to_domain.)
142 * In some cases pg_cast specifies a type coercion function that also
143 * applies length conversion, and in those cases only, the result will
144 * already be properly coerced to the specified typmod.
146 * pstate is only used in the case that we are able to resolve the type of
147 * a previously UNKNOWN Param. It is okay to pass pstate = NULL if the
148 * caller does not want type information updated for Params.
150 * Note: this function must not modify the given expression tree, only add
151 * decoration on top of it. See transformSetOperationTree, for example.
154 coerce_type(ParseState *pstate, Node *node,
155 Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
156 CoercionContext ccontext, CoercionForm cformat, int location)
159 CoercionPathType pathtype;
162 if (targetTypeId == inputTypeId ||
165 /* no conversion needed */
168 if (targetTypeId == ANYOID ||
169 targetTypeId == ANYELEMENTOID ||
170 targetTypeId == ANYNONARRAYOID)
173 * Assume can_coerce_type verified that implicit coercion is okay.
175 * Note: by returning the unmodified node here, we are saying that
176 * it's OK to treat an UNKNOWN constant as a valid input for a
177 * function accepting ANY, ANYELEMENT, or ANYNONARRAY. This should be
178 * all right, since an UNKNOWN value is still a perfectly valid Datum.
180 * NB: we do NOT want a RelabelType here: the exposed type of the
181 * function argument must be its actual type, not the polymorphic
186 if (targetTypeId == ANYARRAYOID ||
187 targetTypeId == ANYENUMOID ||
188 targetTypeId == ANYRANGEOID)
191 * Assume can_coerce_type verified that implicit coercion is okay.
193 * These cases are unlike the ones above because the exposed type of
194 * the argument must be an actual array, enum, or range type. In
195 * particular the argument must *not* be an UNKNOWN constant. If it
196 * is, we just fall through; below, we'll call anyarray_in,
197 * anyenum_in, or anyrange_in, which will produce an error. Also, if
198 * what we have is a domain over array, enum, or range, we have to
199 * relabel it to its base type.
201 * Note: currently, we can't actually see a domain-over-enum here,
202 * since the other functions in this file will not match such a
203 * parameter to ANYENUM. But that should get changed eventually.
205 if (inputTypeId != UNKNOWNOID)
207 Oid baseTypeId = getBaseType(inputTypeId);
209 if (baseTypeId != inputTypeId)
211 RelabelType *r = makeRelabelType((Expr *) node,
216 r->location = location;
219 /* Not a domain type, so return it as-is */
223 if (inputTypeId == UNKNOWNOID && IsA(node, Const))
226 * Input is a string constant with previously undetermined type. Apply
227 * the target type's typinput function to it to produce a constant of
230 * NOTE: this case cannot be folded together with the other
231 * constant-input case, since the typinput function does not
232 * necessarily behave the same as a type conversion function. For
233 * example, int4's typinput function will reject "1.2", whereas
234 * float-to-int type conversion will round to integer.
236 * XXX if the typinput function is not immutable, we really ought to
237 * postpone evaluation of the function call until runtime. But there
238 * is no way to represent a typinput function call as an expression
239 * tree, because C-string values are not Datums. (XXX This *is*
240 * possible as of 7.3, do we want to do it?)
242 Const *con = (Const *) node;
243 Const *newcon = makeNode(Const);
248 ParseCallbackState pcbstate;
251 * If the target type is a domain, we want to call its base type's
252 * input routine, not domain_in(). This is to avoid premature failure
253 * when the domain applies a typmod: existing input routines follow
254 * implicit-coercion semantics for length checks, which is not always
255 * what we want here. The needed check will be applied properly
256 * inside coerce_to_domain().
258 baseTypeMod = targetTypeMod;
259 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
262 * For most types we pass typmod -1 to the input routine, because
263 * existing input routines follow implicit-coercion semantics for
264 * length checks, which is not always what we want here. Any length
265 * constraint will be applied later by our caller. An exception
266 * however is the INTERVAL type, for which we *must* pass the typmod
267 * or it won't be able to obey the bizarre SQL-spec input rules. (Ugly
268 * as sin, but so is this part of the spec...)
270 if (baseTypeId == INTERVALOID)
271 inputTypeMod = baseTypeMod;
275 targetType = typeidType(baseTypeId);
277 newcon->consttype = baseTypeId;
278 newcon->consttypmod = inputTypeMod;
279 newcon->constcollid = typeTypeCollation(targetType);
280 newcon->constlen = typeLen(targetType);
281 newcon->constbyval = typeByVal(targetType);
282 newcon->constisnull = con->constisnull;
285 * We use the original literal's location regardless of the position
286 * of the coercion. This is a change from pre-9.2 behavior, meant to
287 * simplify life for pg_stat_statements.
289 newcon->location = con->location;
292 * Set up to point at the constant's text if the input routine throws
295 setup_parser_errposition_callback(&pcbstate, pstate, con->location);
298 * We assume here that UNKNOWN's internal representation is the same
301 if (!con->constisnull)
302 newcon->constvalue = stringTypeDatum(targetType,
303 DatumGetCString(con->constvalue),
306 newcon->constvalue = stringTypeDatum(targetType,
310 cancel_parser_errposition_callback(&pcbstate);
312 result = (Node *) newcon;
314 /* If target is a domain, apply constraints. */
315 if (baseTypeId != targetTypeId)
316 result = coerce_to_domain(result,
317 baseTypeId, baseTypeMod,
319 cformat, location, false, false);
321 ReleaseSysCache(targetType);
325 if (IsA(node, Param) &&
326 pstate != NULL && pstate->p_coerce_param_hook != NULL)
329 * Allow the CoerceParamHook to decide what happens. It can return a
330 * transformed node (very possibly the same Param node), or return
331 * NULL to indicate we should proceed with normal coercion.
333 result = (*pstate->p_coerce_param_hook) (pstate,
341 if (IsA(node, CollateExpr))
344 * If we have a COLLATE clause, we have to push the coercion
345 * underneath the COLLATE. This is really ugly, but there is little
346 * choice because the above hacks on Consts and Params wouldn't happen
347 * otherwise. This kluge has consequences in coerce_to_target_type.
349 CollateExpr *coll = (CollateExpr *) node;
350 CollateExpr *newcoll = makeNode(CollateExpr);
352 newcoll->arg = (Expr *)
353 coerce_type(pstate, (Node *) coll->arg,
354 inputTypeId, targetTypeId, targetTypeMod,
355 ccontext, cformat, location);
356 newcoll->collOid = coll->collOid;
357 newcoll->location = coll->location;
358 return (Node *) newcoll;
360 pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
362 if (pathtype != COERCION_PATH_NONE)
364 if (pathtype != COERCION_PATH_RELABELTYPE)
367 * Generate an expression tree representing run-time application
368 * of the conversion function. If we are dealing with a domain
369 * target type, the conversion function will yield the base type,
370 * and we need to extract the correct typmod to use from the
371 * domain's typtypmod.
376 baseTypeMod = targetTypeMod;
377 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
379 result = build_coercion_expression(node, pathtype, funcId,
380 baseTypeId, baseTypeMod,
382 (cformat != COERCE_IMPLICIT_CAST));
385 * If domain, coerce to the domain type and relabel with domain
386 * type ID. We can skip the internal length-coercion step if the
387 * selected coercion function was a type-and-length coercion.
389 if (targetTypeId != baseTypeId)
390 result = coerce_to_domain(result, baseTypeId, baseTypeMod,
392 cformat, location, true,
393 exprIsLengthCoercion(result,
399 * We don't need to do a physical conversion, but we do need to
400 * attach a RelabelType node so that the expression will be seen
401 * to have the intended type when inspected by higher-level code.
403 * Also, domains may have value restrictions beyond the base type
404 * that must be accounted for. If the destination is a domain
405 * then we won't need a RelabelType node.
407 result = coerce_to_domain(node, InvalidOid, -1, targetTypeId,
408 cformat, location, false, false);
412 * XXX could we label result with exprTypmod(node) instead of
413 * default -1 typmod, to save a possible length-coercion
414 * later? Would work if both types have same interpretation of
415 * typmod, which is likely but not certain.
417 RelabelType *r = makeRelabelType((Expr *) result,
422 r->location = location;
428 if (inputTypeId == RECORDOID &&
429 ISCOMPLEX(targetTypeId))
431 /* Coerce a RECORD to a specific complex type */
432 return coerce_record_to_complex(pstate, node, targetTypeId,
433 ccontext, cformat, location);
435 if (targetTypeId == RECORDOID &&
436 ISCOMPLEX(inputTypeId))
438 /* Coerce a specific complex type to RECORD */
439 /* NB: we do NOT want a RelabelType here */
443 if (inputTypeId == RECORDARRAYOID &&
444 is_complex_array(targetTypeId))
446 /* Coerce record[] to a specific complex array type */
447 /* not implemented yet ... */
450 if (targetTypeId == RECORDARRAYOID &&
451 is_complex_array(inputTypeId))
453 /* Coerce a specific complex array type to record[] */
454 /* NB: we do NOT want a RelabelType here */
457 if (typeInheritsFrom(inputTypeId, targetTypeId)
458 || typeIsOfTypedTable(inputTypeId, targetTypeId))
461 * Input class type is a subclass of target, so generate an
462 * appropriate runtime conversion (removing unneeded columns and
463 * possibly rearranging the ones that are wanted).
465 ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
467 r->arg = (Expr *) node;
468 r->resulttype = targetTypeId;
469 r->convertformat = cformat;
470 r->location = location;
473 /* If we get here, caller blew it */
474 elog(ERROR, "failed to find conversion function from %s to %s",
475 format_type_be(inputTypeId), format_type_be(targetTypeId));
476 return NULL; /* keep compiler quiet */
482 * Can input_typeids be coerced to target_typeids?
484 * We must be told the context (CAST construct, assignment, implicit coercion)
485 * as this determines the set of available casts.
488 can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids,
489 CoercionContext ccontext)
491 bool have_generics = false;
494 /* run through argument list... */
495 for (i = 0; i < nargs; i++)
497 Oid inputTypeId = input_typeids[i];
498 Oid targetTypeId = target_typeids[i];
499 CoercionPathType pathtype;
502 /* no problem if same type */
503 if (inputTypeId == targetTypeId)
506 /* accept if target is ANY */
507 if (targetTypeId == ANYOID)
510 /* accept if target is polymorphic, for now */
511 if (IsPolymorphicType(targetTypeId))
513 have_generics = true; /* do more checking later */
518 * If input is an untyped string constant, assume we can convert it to
521 if (inputTypeId == UNKNOWNOID)
525 * If pg_cast shows that we can coerce, accept. This test now covers
526 * both binary-compatible and coercion-function cases.
528 pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
530 if (pathtype != COERCION_PATH_NONE)
534 * If input is RECORD and target is a composite type, assume we can
535 * coerce (may need tighter checking here)
537 if (inputTypeId == RECORDOID &&
538 ISCOMPLEX(targetTypeId))
542 * If input is a composite type and target is RECORD, accept
544 if (targetTypeId == RECORDOID &&
545 ISCOMPLEX(inputTypeId))
548 #ifdef NOT_USED /* not implemented yet */
551 * If input is record[] and target is a composite array type, assume
552 * we can coerce (may need tighter checking here)
554 if (inputTypeId == RECORDARRAYOID &&
555 is_complex_array(targetTypeId))
560 * If input is a composite array type and target is record[], accept
562 if (targetTypeId == RECORDARRAYOID &&
563 is_complex_array(inputTypeId))
567 * If input is a class type that inherits from target, accept
569 if (typeInheritsFrom(inputTypeId, targetTypeId)
570 || typeIsOfTypedTable(inputTypeId, targetTypeId))
574 * Else, cannot coerce at this argument position
579 /* If we found any generic argument types, cross-check them */
582 if (!check_generic_type_consistency(input_typeids, target_typeids,
592 * Create an expression tree to represent coercion to a domain type.
594 * 'arg': input expression
595 * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
596 * has not bothered to look this up)
597 * 'baseTypeMod': base type typmod of domain, if known (pass -1 if caller
598 * has not bothered to look this up)
599 * 'typeId': target type to coerce to
600 * 'cformat': coercion format
601 * 'location': coercion request location
602 * 'hideInputCoercion': if true, hide the input coercion under this one.
603 * 'lengthCoercionDone': if true, caller already accounted for length,
604 * ie the input is already of baseTypMod as well as baseTypeId.
606 * If the target type isn't a domain, the given 'arg' is returned as-is.
609 coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId,
610 CoercionForm cformat, int location,
611 bool hideInputCoercion,
612 bool lengthCoercionDone)
614 CoerceToDomain *result;
616 /* Get the base type if it hasn't been supplied */
617 if (baseTypeId == InvalidOid)
618 baseTypeId = getBaseTypeAndTypmod(typeId, &baseTypeMod);
620 /* If it isn't a domain, return the node as it was passed in */
621 if (baseTypeId == typeId)
624 /* Suppress display of nested coercion steps */
625 if (hideInputCoercion)
626 hide_coercion_node(arg);
629 * If the domain applies a typmod to its base type, build the appropriate
630 * coercion step. Mark it implicit for display purposes, because we don't
631 * want it shown separately by ruleutils.c; but the isExplicit flag passed
632 * to the conversion function depends on the manner in which the domain
633 * coercion is invoked, so that the semantics of implicit and explicit
634 * coercion differ. (Is that really the behavior we want?)
636 * NOTE: because we apply this as part of the fixed expression structure,
637 * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that that
638 * would be safe to do anyway, without lots of knowledge about what the
639 * base type thinks the typmod means.
641 if (!lengthCoercionDone)
643 if (baseTypeMod >= 0)
644 arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
645 COERCE_IMPLICIT_CAST, location,
646 (cformat != COERCE_IMPLICIT_CAST),
651 * Now build the domain coercion node. This represents run-time checking
652 * of any constraints currently attached to the domain. This also ensures
653 * that the expression is properly labeled as to result type.
655 result = makeNode(CoerceToDomain);
656 result->arg = (Expr *) arg;
657 result->resulttype = typeId;
658 result->resulttypmod = -1; /* currently, always -1 for domains */
659 /* resultcollid will be set by parse_collate.c */
660 result->coercionformat = cformat;
661 result->location = location;
663 return (Node *) result;
668 * coerce_type_typmod()
669 * Force a value to a particular typmod, if meaningful and possible.
671 * This is applied to values that are going to be stored in a relation
672 * (where we have an atttypmod for the column) as well as values being
673 * explicitly CASTed (where the typmod comes from the target type spec).
675 * The caller must have already ensured that the value is of the correct
676 * type, typically by applying coerce_type.
678 * cformat determines the display properties of the generated node (if any),
679 * while isExplicit may affect semantics. If hideInputCoercion is true
680 * *and* we generate a node, the input node is forced to IMPLICIT display
681 * form, so that only the typmod coercion node will be visible when
682 * displaying the expression.
684 * NOTE: this does not need to work on domain types, because any typmod
685 * coercion for a domain is considered to be part of the type coercion
686 * needed to produce the domain value in the first place. So, no getBaseType.
689 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
690 CoercionForm cformat, int location,
691 bool isExplicit, bool hideInputCoercion)
693 CoercionPathType pathtype;
697 * A negative typmod is assumed to mean that no coercion is wanted. Also,
698 * skip coercion if already done.
700 if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
703 pathtype = find_typmod_coercion_function(targetTypeId, &funcId);
705 if (pathtype != COERCION_PATH_NONE)
707 /* Suppress display of nested coercion steps */
708 if (hideInputCoercion)
709 hide_coercion_node(node);
711 node = build_coercion_expression(node, pathtype, funcId,
712 targetTypeId, targetTypMod,
721 * Mark a coercion node as IMPLICIT so it will never be displayed by
722 * ruleutils.c. We use this when we generate a nest of coercion nodes
723 * to implement what is logically one conversion; the inner nodes are
724 * forced to IMPLICIT_CAST format. This does not change their semantics,
725 * only display behavior.
727 * It is caller error to call this on something that doesn't have a
728 * CoercionForm field.
731 hide_coercion_node(Node *node)
733 if (IsA(node, FuncExpr))
734 ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
735 else if (IsA(node, RelabelType))
736 ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
737 else if (IsA(node, CoerceViaIO))
738 ((CoerceViaIO *) node)->coerceformat = COERCE_IMPLICIT_CAST;
739 else if (IsA(node, ArrayCoerceExpr))
740 ((ArrayCoerceExpr *) node)->coerceformat = COERCE_IMPLICIT_CAST;
741 else if (IsA(node, ConvertRowtypeExpr))
742 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
743 else if (IsA(node, RowExpr))
744 ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
745 else if (IsA(node, CoerceToDomain))
746 ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
748 elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
752 * build_coercion_expression()
753 * Construct an expression tree for applying a pg_cast entry.
755 * This is used for both type-coercion and length-coercion operations,
756 * since there is no difference in terms of the calling convention.
759 build_coercion_expression(Node *node,
760 CoercionPathType pathtype,
762 Oid targetTypeId, int32 targetTypMod,
763 CoercionForm cformat, int location,
768 if (OidIsValid(funcId))
771 Form_pg_proc procstruct;
773 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcId));
774 if (!HeapTupleIsValid(tp))
775 elog(ERROR, "cache lookup failed for function %u", funcId);
776 procstruct = (Form_pg_proc) GETSTRUCT(tp);
779 * These Asserts essentially check that function is a legal coercion
780 * function. We can't make the seemingly obvious tests on prorettype
781 * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
782 * various binary-compatibility cases.
784 /* Assert(targetTypeId == procstruct->prorettype); */
785 Assert(!procstruct->proretset);
786 Assert(!procstruct->proisagg);
787 Assert(!procstruct->proiswindow);
788 nargs = procstruct->pronargs;
789 Assert(nargs >= 1 && nargs <= 3);
790 /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
791 Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
792 Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
797 if (pathtype == COERCION_PATH_FUNC)
799 /* We build an ordinary FuncExpr with special arguments */
804 Assert(OidIsValid(funcId));
806 args = list_make1(node);
810 /* Pass target typmod as an int4 constant */
811 cons = makeConst(INT4OID,
815 Int32GetDatum(targetTypMod),
819 args = lappend(args, cons);
824 /* Pass it a boolean isExplicit parameter, too */
825 cons = makeConst(BOOLOID,
829 BoolGetDatum(isExplicit),
833 args = lappend(args, cons);
836 fexpr = makeFuncExpr(funcId, targetTypeId, args,
837 InvalidOid, InvalidOid, cformat);
838 fexpr->location = location;
839 return (Node *) fexpr;
841 else if (pathtype == COERCION_PATH_ARRAYCOERCE)
843 /* We need to build an ArrayCoerceExpr */
844 ArrayCoerceExpr *acoerce = makeNode(ArrayCoerceExpr);
846 acoerce->arg = (Expr *) node;
847 acoerce->elemfuncid = funcId;
848 acoerce->resulttype = targetTypeId;
851 * Label the output as having a particular typmod only if we are
852 * really invoking a length-coercion function, ie one with more than
855 acoerce->resulttypmod = (nargs >= 2) ? targetTypMod : -1;
856 /* resultcollid will be set by parse_collate.c */
857 acoerce->isExplicit = isExplicit;
858 acoerce->coerceformat = cformat;
859 acoerce->location = location;
861 return (Node *) acoerce;
863 else if (pathtype == COERCION_PATH_COERCEVIAIO)
865 /* We need to build a CoerceViaIO node */
866 CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
868 Assert(!OidIsValid(funcId));
870 iocoerce->arg = (Expr *) node;
871 iocoerce->resulttype = targetTypeId;
872 /* resultcollid will be set by parse_collate.c */
873 iocoerce->coerceformat = cformat;
874 iocoerce->location = location;
876 return (Node *) iocoerce;
880 elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
882 return NULL; /* keep compiler quiet */
888 * coerce_record_to_complex
889 * Coerce a RECORD to a specific composite type.
891 * Currently we only support this for inputs that are RowExprs or whole-row
895 coerce_record_to_complex(ParseState *pstate, Node *node,
897 CoercionContext ccontext,
898 CoercionForm cformat,
909 if (node && IsA(node, RowExpr))
912 * Since the RowExpr must be of type RECORD, we needn't worry about it
913 * containing any dropped columns.
915 args = ((RowExpr *) node)->args;
917 else if (node && IsA(node, Var) &&
918 ((Var *) node)->varattno == InvalidAttrNumber)
920 int rtindex = ((Var *) node)->varno;
921 int sublevels_up = ((Var *) node)->varlevelsup;
922 int vlocation = ((Var *) node)->location;
925 rte = GetRTEByRangeTablePosn(pstate, rtindex, sublevels_up);
926 expandRTE(rte, rtindex, sublevels_up, vlocation, false,
931 (errcode(ERRCODE_CANNOT_COERCE),
932 errmsg("cannot cast type %s to %s",
933 format_type_be(RECORDOID),
934 format_type_be(targetTypeId)),
935 parser_coercion_errposition(pstate, location, node)));
937 tupdesc = lookup_rowtype_tupdesc(targetTypeId, -1);
940 arg = list_head(args);
941 for (i = 0; i < tupdesc->natts; i++)
947 /* Fill in NULLs for dropped columns in rowtype */
948 if (tupdesc->attrs[i]->attisdropped)
951 * can't use atttypid here, but it doesn't really matter what type
952 * the Const claims to be.
954 newargs = lappend(newargs,
955 makeNullConst(INT4OID, -1, InvalidOid));
961 (errcode(ERRCODE_CANNOT_COERCE),
962 errmsg("cannot cast type %s to %s",
963 format_type_be(RECORDOID),
964 format_type_be(targetTypeId)),
965 errdetail("Input has too few columns."),
966 parser_coercion_errposition(pstate, location, node)));
967 expr = (Node *) lfirst(arg);
968 exprtype = exprType(expr);
970 cexpr = coerce_to_target_type(pstate,
972 tupdesc->attrs[i]->atttypid,
973 tupdesc->attrs[i]->atttypmod,
975 COERCE_IMPLICIT_CAST,
979 (errcode(ERRCODE_CANNOT_COERCE),
980 errmsg("cannot cast type %s to %s",
981 format_type_be(RECORDOID),
982 format_type_be(targetTypeId)),
983 errdetail("Cannot cast type %s to %s in column %d.",
984 format_type_be(exprtype),
985 format_type_be(tupdesc->attrs[i]->atttypid),
987 parser_coercion_errposition(pstate, location, expr)));
988 newargs = lappend(newargs, cexpr);
994 (errcode(ERRCODE_CANNOT_COERCE),
995 errmsg("cannot cast type %s to %s",
996 format_type_be(RECORDOID),
997 format_type_be(targetTypeId)),
998 errdetail("Input has too many columns."),
999 parser_coercion_errposition(pstate, location, node)));
1001 ReleaseTupleDesc(tupdesc);
1003 rowexpr = makeNode(RowExpr);
1004 rowexpr->args = newargs;
1005 rowexpr->row_typeid = targetTypeId;
1006 rowexpr->row_format = cformat;
1007 rowexpr->colnames = NIL; /* not needed for named target type */
1008 rowexpr->location = location;
1009 return (Node *) rowexpr;
1013 * coerce_to_boolean()
1014 * Coerce an argument of a construct that requires boolean input
1015 * (AND, OR, NOT, etc). Also check that input is not a set.
1017 * Returns the possibly-transformed node tree.
1019 * As with coerce_type, pstate may be NULL if no special unknown-Param
1020 * processing is wanted.
1023 coerce_to_boolean(ParseState *pstate, Node *node,
1024 const char *constructName)
1026 Oid inputTypeId = exprType(node);
1028 if (inputTypeId != BOOLOID)
1032 newnode = coerce_to_target_type(pstate, node, inputTypeId,
1034 COERCION_ASSIGNMENT,
1035 COERCE_IMPLICIT_CAST,
1037 if (newnode == NULL)
1039 (errcode(ERRCODE_DATATYPE_MISMATCH),
1040 /* translator: first %s is name of a SQL construct, eg WHERE */
1041 errmsg("argument of %s must be type boolean, not type %s",
1042 constructName, format_type_be(inputTypeId)),
1043 parser_errposition(pstate, exprLocation(node))));
1047 if (expression_returns_set(node))
1049 (errcode(ERRCODE_DATATYPE_MISMATCH),
1050 /* translator: %s is name of a SQL construct, eg WHERE */
1051 errmsg("argument of %s must not return a set",
1053 parser_errposition(pstate, exprLocation(node))));
1059 * coerce_to_specific_type()
1060 * Coerce an argument of a construct that requires a specific data type.
1061 * Also check that input is not a set.
1063 * Returns the possibly-transformed node tree.
1065 * As with coerce_type, pstate may be NULL if no special unknown-Param
1066 * processing is wanted.
1069 coerce_to_specific_type(ParseState *pstate, Node *node,
1071 const char *constructName)
1073 Oid inputTypeId = exprType(node);
1075 if (inputTypeId != targetTypeId)
1079 newnode = coerce_to_target_type(pstate, node, inputTypeId,
1081 COERCION_ASSIGNMENT,
1082 COERCE_IMPLICIT_CAST,
1084 if (newnode == NULL)
1086 (errcode(ERRCODE_DATATYPE_MISMATCH),
1087 /* translator: first %s is name of a SQL construct, eg LIMIT */
1088 errmsg("argument of %s must be type %s, not type %s",
1090 format_type_be(targetTypeId),
1091 format_type_be(inputTypeId)),
1092 parser_errposition(pstate, exprLocation(node))));
1096 if (expression_returns_set(node))
1098 (errcode(ERRCODE_DATATYPE_MISMATCH),
1099 /* translator: %s is name of a SQL construct, eg LIMIT */
1100 errmsg("argument of %s must not return a set",
1102 parser_errposition(pstate, exprLocation(node))));
1109 * parser_coercion_errposition - report coercion error location, if possible
1111 * We prefer to point at the coercion request (CAST, ::, etc) if possible;
1112 * but there may be no such location in the case of an implicit coercion.
1113 * In that case point at the input expression.
1115 * XXX possibly this is more generally useful than coercion errors;
1116 * if so, should rename and place with parser_errposition.
1119 parser_coercion_errposition(ParseState *pstate,
1120 int coerce_location,
1123 if (coerce_location >= 0)
1124 return parser_errposition(pstate, coerce_location);
1126 return parser_errposition(pstate, exprLocation(input_expr));
1131 * select_common_type()
1132 * Determine the common supertype of a list of input expressions.
1133 * This is used for determining the output type of CASE, UNION,
1134 * and similar constructs.
1136 * 'exprs' is a *nonempty* list of expressions. Note that earlier items
1137 * in the list will be preferred if there is doubt.
1138 * 'context' is a phrase to use in the error message if we fail to select
1139 * a usable type. Pass NULL to have the routine return InvalidOid
1140 * rather than throwing an error on failure.
1141 * 'which_expr': if not NULL, receives a pointer to the particular input
1142 * expression from which the result type was taken.
1145 select_common_type(ParseState *pstate, List *exprs, const char *context,
1150 TYPCATEGORY pcategory;
1154 Assert(exprs != NIL);
1155 pexpr = (Node *) linitial(exprs);
1156 lc = lnext(list_head(exprs));
1157 ptype = exprType(pexpr);
1160 * If all input types are valid and exactly the same, just pick that type.
1161 * This is the only way that we will resolve the result as being a domain
1162 * type; otherwise domains are smashed to their base types for comparison.
1164 if (ptype != UNKNOWNOID)
1166 for_each_cell(lc, lc)
1168 Node *nexpr = (Node *) lfirst(lc);
1169 Oid ntype = exprType(nexpr);
1174 if (lc == NULL) /* got to the end of the list? */
1177 *which_expr = pexpr;
1183 * Nope, so set up for the full algorithm. Note that at this point, lc
1184 * points to the first list item with type different from pexpr's; we need
1185 * not re-examine any items the previous loop advanced over.
1187 ptype = getBaseType(ptype);
1188 get_type_category_preferred(ptype, &pcategory, &pispreferred);
1190 for_each_cell(lc, lc)
1192 Node *nexpr = (Node *) lfirst(lc);
1193 Oid ntype = getBaseType(exprType(nexpr));
1195 /* move on to next one if no new information... */
1196 if (ntype != UNKNOWNOID && ntype != ptype)
1198 TYPCATEGORY ncategory;
1201 get_type_category_preferred(ntype, &ncategory, &nispreferred);
1202 if (ptype == UNKNOWNOID)
1204 /* so far, only unknowns so take anything... */
1207 pcategory = ncategory;
1208 pispreferred = nispreferred;
1210 else if (ncategory != pcategory)
1213 * both types in different categories? then not much hope...
1215 if (context == NULL)
1218 (errcode(ERRCODE_DATATYPE_MISMATCH),
1220 translator: first %s is name of a SQL construct, eg CASE */
1221 errmsg("%s types %s and %s cannot be matched",
1223 format_type_be(ptype),
1224 format_type_be(ntype)),
1225 parser_errposition(pstate, exprLocation(nexpr))));
1227 else if (!pispreferred &&
1228 can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1229 !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1232 * take new type if can coerce to it implicitly but not the
1233 * other way; but if we have a preferred type, stay on it.
1237 pcategory = ncategory;
1238 pispreferred = nispreferred;
1244 * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1245 * then resolve as type TEXT. This situation comes up with constructs
1246 * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1247 * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1248 * output type as UNKNOWN, but that really doesn't work, because we'd
1249 * probably end up needing a runtime coercion from UNKNOWN to something
1250 * else, and we usually won't have it. We need to coerce the unknown
1251 * literals while they are still literals, so a decision has to be made
1254 if (ptype == UNKNOWNOID)
1258 *which_expr = pexpr;
1263 * coerce_to_common_type()
1264 * Coerce an expression to the given type.
1266 * This is used following select_common_type() to coerce the individual
1267 * expressions to the desired type. 'context' is a phrase to use in the
1268 * error message if we fail to coerce.
1270 * As with coerce_type, pstate may be NULL if no special unknown-Param
1271 * processing is wanted.
1274 coerce_to_common_type(ParseState *pstate, Node *node,
1275 Oid targetTypeId, const char *context)
1277 Oid inputTypeId = exprType(node);
1279 if (inputTypeId == targetTypeId)
1280 return node; /* no work */
1281 if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
1282 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1283 COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
1286 (errcode(ERRCODE_CANNOT_COERCE),
1287 /* translator: first %s is name of a SQL construct, eg CASE */
1288 errmsg("%s could not convert type %s to %s",
1290 format_type_be(inputTypeId),
1291 format_type_be(targetTypeId)),
1292 parser_errposition(pstate, exprLocation(node))));
1297 * check_generic_type_consistency()
1298 * Are the actual arguments potentially compatible with a
1299 * polymorphic function?
1301 * The argument consistency rules are:
1303 * 1) All arguments declared ANYELEMENT must have the same datatype.
1304 * 2) All arguments declared ANYARRAY must have the same datatype,
1305 * which must be a varlena array type.
1306 * 3) All arguments declared ANYRANGE must have the same datatype,
1307 * which must be a range type.
1308 * 4) If there are arguments of both ANYELEMENT and ANYARRAY, make sure the
1309 * actual ANYELEMENT datatype is in fact the element type for the actual
1310 * ANYARRAY datatype.
1311 * 5) Similarly, if there are arguments of both ANYELEMENT and ANYRANGE,
1312 * make sure the actual ANYELEMENT datatype is in fact the subtype for
1313 * the actual ANYRANGE type.
1314 * 6) ANYENUM is treated the same as ANYELEMENT except that if it is used
1315 * (alone or in combination with plain ANYELEMENT), we add the extra
1316 * condition that the ANYELEMENT type must be an enum.
1317 * 7) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1318 * we add the extra condition that the ANYELEMENT type must not be an array.
1319 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1320 * is an extra restriction if not.)
1322 * Domains over arrays match ANYARRAY, and are immediately flattened to their
1323 * base type. (Thus, for example, we will consider it a match if one ANYARRAY
1324 * argument is a domain over int4[] while another one is just int4[].) Also
1325 * notice that such a domain does *not* match ANYNONARRAY.
1327 * Similarly, domains over ranges match ANYRANGE, and are immediately
1328 * flattened to their base type.
1330 * Note that domains aren't currently considered to match ANYENUM,
1331 * even if their base type would match.
1333 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1334 * argument, assume it is okay.
1336 * If an input is of type ANYARRAY (ie, we know it's an array, but not
1337 * what element type), we will accept it as a match to an argument declared
1338 * ANYARRAY, so long as we don't have to determine an element type ---
1339 * that is, so long as there is no use of ANYELEMENT. This is mostly for
1340 * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
1342 * We do not ereport here, but just return FALSE if a rule is violated.
1345 check_generic_type_consistency(Oid *actual_arg_types,
1346 Oid *declared_arg_types,
1350 Oid elem_typeid = InvalidOid;
1351 Oid array_typeid = InvalidOid;
1353 Oid range_typeid = InvalidOid;
1355 bool have_anyelement = false;
1356 bool have_anynonarray = false;
1357 bool have_anyenum = false;
1360 * Loop through the arguments to see if we have any that are polymorphic.
1361 * If so, require the actual types to be consistent.
1363 for (j = 0; j < nargs; j++)
1365 Oid decl_type = declared_arg_types[j];
1366 Oid actual_type = actual_arg_types[j];
1368 if (decl_type == ANYELEMENTOID ||
1369 decl_type == ANYNONARRAYOID ||
1370 decl_type == ANYENUMOID)
1372 have_anyelement = true;
1373 if (decl_type == ANYNONARRAYOID)
1374 have_anynonarray = true;
1375 else if (decl_type == ANYENUMOID)
1376 have_anyenum = true;
1377 if (actual_type == UNKNOWNOID)
1379 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1381 elem_typeid = actual_type;
1383 else if (decl_type == ANYARRAYOID)
1385 if (actual_type == UNKNOWNOID)
1387 actual_type = getBaseType(actual_type); /* flatten domains */
1388 if (OidIsValid(array_typeid) && actual_type != array_typeid)
1390 array_typeid = actual_type;
1392 else if (decl_type == ANYRANGEOID)
1394 if (actual_type == UNKNOWNOID)
1396 actual_type = getBaseType(actual_type); /* flatten domains */
1397 if (OidIsValid(range_typeid) && actual_type != range_typeid)
1399 range_typeid = actual_type;
1403 /* Get the element type based on the array type, if we have one */
1404 if (OidIsValid(array_typeid))
1406 if (array_typeid == ANYARRAYOID)
1408 /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1409 if (have_anyelement)
1414 array_typelem = get_element_type(array_typeid);
1415 if (!OidIsValid(array_typelem))
1416 return false; /* should be an array, but isn't */
1418 if (!OidIsValid(elem_typeid))
1421 * if we don't have an element type yet, use the one we just got
1423 elem_typeid = array_typelem;
1425 else if (array_typelem != elem_typeid)
1427 /* otherwise, they better match */
1432 /* Get the element type based on the range type, if we have one */
1433 if (OidIsValid(range_typeid))
1435 range_typelem = get_range_subtype(range_typeid);
1436 if (!OidIsValid(range_typelem))
1437 return false; /* should be a range, but isn't */
1439 if (!OidIsValid(elem_typeid))
1442 * if we don't have an element type yet, use the one we just got
1444 elem_typeid = range_typelem;
1446 else if (range_typelem != elem_typeid)
1448 /* otherwise, they better match */
1453 if (have_anynonarray)
1455 /* require the element type to not be an array or domain over array */
1456 if (type_is_array_domain(elem_typeid))
1462 /* require the element type to be an enum */
1463 if (!type_is_enum(elem_typeid))
1472 * enforce_generic_type_consistency()
1473 * Make sure a polymorphic function is legally callable, and
1474 * deduce actual argument and result types.
1476 * If any polymorphic pseudotype is used in a function's arguments or
1477 * return type, we make sure the actual data types are consistent with
1478 * each other. The argument consistency rules are shown above for
1479 * check_generic_type_consistency().
1481 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1482 * argument, we attempt to deduce the actual type it should have. If
1483 * successful, we alter that position of declared_arg_types[] so that
1484 * make_fn_arguments will coerce the literal to the right thing.
1486 * Rules are applied to the function's return type (possibly altering it)
1487 * if it is declared as a polymorphic type:
1489 * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1490 * argument's actual type as the function's return type.
1491 * 2) Similarly, if return type is ANYRANGE, and any argument is ANYRANGE,
1492 * use the argument's actual type as the function's return type.
1493 * 3) If return type is ANYARRAY, no argument is ANYARRAY, but any argument is
1494 * ANYELEMENT, use the actual type of the argument to determine the
1495 * function's return type, i.e. the element type's corresponding array
1496 * type. (Note: similar behavior does not exist for ANYRANGE, because it's
1497 * impossible to determine the range type from the subtype alone.)
1498 * 4) If return type is ANYARRAY, but no argument is ANYARRAY or ANYELEMENT,
1499 * generate an error. Similarly, if return type is ANYRANGE, but no
1500 * argument is ANYRANGE, generate an error. (These conditions are
1501 * prevented by CREATE FUNCTION and therefore are not expected here.)
1502 * 5) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1503 * argument's actual type as the function's return type.
1504 * 6) If return type is ANYELEMENT, no argument is ANYELEMENT, but any argument
1505 * is ANYARRAY or ANYRANGE, use the actual type of the argument to determine
1506 * the function's return type, i.e. the array type's corresponding element
1507 * type or the range type's corresponding subtype (or both, in which case
1509 * 7) If return type is ANYELEMENT, no argument is ANYELEMENT, ANYARRAY, or
1510 * ANYRANGE, generate an error. (This condition is prevented by CREATE
1511 * FUNCTION and therefore is not expected here.)
1512 * 8) ANYENUM is treated the same as ANYELEMENT except that if it is used
1513 * (alone or in combination with plain ANYELEMENT), we add the extra
1514 * condition that the ANYELEMENT type must be an enum.
1515 * 9) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1516 * we add the extra condition that the ANYELEMENT type must not be an array.
1517 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1518 * is an extra restriction if not.)
1520 * Domains over arrays or ranges match ANYARRAY or ANYRANGE arguments,
1521 * respectively, and are immediately flattened to their base type. (In
1522 * particular, if the return type is also ANYARRAY or ANYRANGE, we'll set it
1523 * to the base type not the domain type.)
1525 * When allow_poly is false, we are not expecting any of the actual_arg_types
1526 * to be polymorphic, and we should not return a polymorphic result type
1527 * either. When allow_poly is true, it is okay to have polymorphic "actual"
1528 * arg types, and we can return ANYARRAY, ANYRANGE, or ANYELEMENT as the
1529 * result. (This case is currently used only to check compatibility of an
1530 * aggregate's declaration with the underlying transfn.)
1532 * A special case is that we could see ANYARRAY as an actual_arg_type even
1533 * when allow_poly is false (this is possible only because pg_statistic has
1534 * columns shown as anyarray in the catalogs). We allow this to match a
1535 * declared ANYARRAY argument, but only if there is no ANYELEMENT argument
1536 * or result (since we can't determine a specific element type to match to
1537 * ANYELEMENT). Note this means that functions taking ANYARRAY had better
1538 * behave sanely if applied to the pg_statistic columns; they can't just
1539 * assume that successive inputs are of the same actual element type.
1542 enforce_generic_type_consistency(Oid *actual_arg_types,
1543 Oid *declared_arg_types,
1549 bool have_generics = false;
1550 bool have_unknowns = false;
1551 Oid elem_typeid = InvalidOid;
1552 Oid array_typeid = InvalidOid;
1553 Oid range_typeid = InvalidOid;
1556 bool have_anyelement = (rettype == ANYELEMENTOID ||
1557 rettype == ANYNONARRAYOID ||
1558 rettype == ANYENUMOID);
1559 bool have_anynonarray = (rettype == ANYNONARRAYOID);
1560 bool have_anyenum = (rettype == ANYENUMOID);
1563 * Loop through the arguments to see if we have any that are polymorphic.
1564 * If so, require the actual types to be consistent.
1566 for (j = 0; j < nargs; j++)
1568 Oid decl_type = declared_arg_types[j];
1569 Oid actual_type = actual_arg_types[j];
1571 if (decl_type == ANYELEMENTOID ||
1572 decl_type == ANYNONARRAYOID ||
1573 decl_type == ANYENUMOID)
1575 have_generics = have_anyelement = true;
1576 if (decl_type == ANYNONARRAYOID)
1577 have_anynonarray = true;
1578 else if (decl_type == ANYENUMOID)
1579 have_anyenum = true;
1580 if (actual_type == UNKNOWNOID)
1582 have_unknowns = true;
1585 if (allow_poly && decl_type == actual_type)
1586 continue; /* no new information here */
1587 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1589 (errcode(ERRCODE_DATATYPE_MISMATCH),
1590 errmsg("arguments declared \"anyelement\" are not all alike"),
1591 errdetail("%s versus %s",
1592 format_type_be(elem_typeid),
1593 format_type_be(actual_type))));
1594 elem_typeid = actual_type;
1596 else if (decl_type == ANYARRAYOID)
1598 have_generics = true;
1599 if (actual_type == UNKNOWNOID)
1601 have_unknowns = true;
1604 if (allow_poly && decl_type == actual_type)
1605 continue; /* no new information here */
1606 actual_type = getBaseType(actual_type); /* flatten domains */
1607 if (OidIsValid(array_typeid) && actual_type != array_typeid)
1609 (errcode(ERRCODE_DATATYPE_MISMATCH),
1610 errmsg("arguments declared \"anyarray\" are not all alike"),
1611 errdetail("%s versus %s",
1612 format_type_be(array_typeid),
1613 format_type_be(actual_type))));
1614 array_typeid = actual_type;
1616 else if (decl_type == ANYRANGEOID)
1618 have_generics = true;
1619 if (actual_type == UNKNOWNOID)
1621 have_unknowns = true;
1624 if (allow_poly && decl_type == actual_type)
1625 continue; /* no new information here */
1626 actual_type = getBaseType(actual_type); /* flatten domains */
1627 if (OidIsValid(range_typeid) && actual_type != range_typeid)
1629 (errcode(ERRCODE_DATATYPE_MISMATCH),
1630 errmsg("arguments declared \"anyrange\" are not all alike"),
1631 errdetail("%s versus %s",
1632 format_type_be(range_typeid),
1633 format_type_be(actual_type))));
1634 range_typeid = actual_type;
1639 * Fast Track: if none of the arguments are polymorphic, return the
1640 * unmodified rettype. We assume it can't be polymorphic either.
1645 /* Get the element type based on the array type, if we have one */
1646 if (OidIsValid(array_typeid))
1648 if (array_typeid == ANYARRAYOID && !have_anyelement)
1650 /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1651 array_typelem = ANYELEMENTOID;
1655 array_typelem = get_element_type(array_typeid);
1656 if (!OidIsValid(array_typelem))
1658 (errcode(ERRCODE_DATATYPE_MISMATCH),
1659 errmsg("argument declared \"anyarray\" is not an array but type %s",
1660 format_type_be(array_typeid))));
1663 if (!OidIsValid(elem_typeid))
1666 * if we don't have an element type yet, use the one we just got
1668 elem_typeid = array_typelem;
1670 else if (array_typelem != elem_typeid)
1672 /* otherwise, they better match */
1674 (errcode(ERRCODE_DATATYPE_MISMATCH),
1675 errmsg("argument declared \"anyarray\" is not consistent with argument declared \"anyelement\""),
1676 errdetail("%s versus %s",
1677 format_type_be(array_typeid),
1678 format_type_be(elem_typeid))));
1682 /* Get the element type based on the range type, if we have one */
1683 if (OidIsValid(range_typeid))
1685 if (range_typeid == ANYRANGEOID && !have_anyelement)
1687 /* Special case for ANYRANGE input: okay iff no ANYELEMENT */
1688 range_typelem = ANYELEMENTOID;
1692 range_typelem = get_range_subtype(range_typeid);
1693 if (!OidIsValid(range_typelem))
1695 (errcode(ERRCODE_DATATYPE_MISMATCH),
1696 errmsg("argument declared \"anyrange\" is not a range but type %s",
1697 format_type_be(range_typeid))));
1700 if (!OidIsValid(elem_typeid))
1703 * if we don't have an element type yet, use the one we just got
1705 elem_typeid = range_typelem;
1707 else if (range_typelem != elem_typeid)
1709 /* otherwise, they better match */
1711 (errcode(ERRCODE_DATATYPE_MISMATCH),
1712 errmsg("argument declared \"anyrange\" is not consistent with argument declared \"anyelement\""),
1713 errdetail("%s versus %s",
1714 format_type_be(range_typeid),
1715 format_type_be(elem_typeid))));
1719 if (!OidIsValid(elem_typeid))
1723 elem_typeid = ANYELEMENTOID;
1724 array_typeid = ANYARRAYOID;
1725 range_typeid = ANYRANGEOID;
1729 /* Only way to get here is if all the generic args are UNKNOWN */
1731 (errcode(ERRCODE_DATATYPE_MISMATCH),
1732 errmsg("could not determine polymorphic type because input has type \"unknown\"")));
1736 if (have_anynonarray && elem_typeid != ANYELEMENTOID)
1738 /* require the element type to not be an array or domain over array */
1739 if (type_is_array_domain(elem_typeid))
1741 (errcode(ERRCODE_DATATYPE_MISMATCH),
1742 errmsg("type matched to anynonarray is an array type: %s",
1743 format_type_be(elem_typeid))));
1746 if (have_anyenum && elem_typeid != ANYELEMENTOID)
1748 /* require the element type to be an enum */
1749 if (!type_is_enum(elem_typeid))
1751 (errcode(ERRCODE_DATATYPE_MISMATCH),
1752 errmsg("type matched to anyenum is not an enum type: %s",
1753 format_type_be(elem_typeid))));
1757 * If we had any unknown inputs, re-scan to assign correct types
1761 for (j = 0; j < nargs; j++)
1763 Oid decl_type = declared_arg_types[j];
1764 Oid actual_type = actual_arg_types[j];
1766 if (actual_type != UNKNOWNOID)
1769 if (decl_type == ANYELEMENTOID ||
1770 decl_type == ANYNONARRAYOID ||
1771 decl_type == ANYENUMOID)
1772 declared_arg_types[j] = elem_typeid;
1773 else if (decl_type == ANYARRAYOID)
1775 if (!OidIsValid(array_typeid))
1777 array_typeid = get_array_type(elem_typeid);
1778 if (!OidIsValid(array_typeid))
1780 (errcode(ERRCODE_UNDEFINED_OBJECT),
1781 errmsg("could not find array type for data type %s",
1782 format_type_be(elem_typeid))));
1784 declared_arg_types[j] = array_typeid;
1786 else if (decl_type == ANYRANGEOID)
1788 if (!OidIsValid(range_typeid))
1791 (errcode(ERRCODE_UNDEFINED_OBJECT),
1792 errmsg("could not find range type for data type %s",
1793 format_type_be(elem_typeid))));
1795 declared_arg_types[j] = range_typeid;
1800 /* if we return ANYARRAY use the appropriate argument type */
1801 if (rettype == ANYARRAYOID)
1803 if (!OidIsValid(array_typeid))
1805 array_typeid = get_array_type(elem_typeid);
1806 if (!OidIsValid(array_typeid))
1808 (errcode(ERRCODE_UNDEFINED_OBJECT),
1809 errmsg("could not find array type for data type %s",
1810 format_type_be(elem_typeid))));
1812 return array_typeid;
1815 /* if we return ANYRANGE use the appropriate argument type */
1816 if (rettype == ANYRANGEOID)
1818 if (!OidIsValid(range_typeid))
1821 (errcode(ERRCODE_UNDEFINED_OBJECT),
1822 errmsg("could not find range type for data type %s",
1823 format_type_be(elem_typeid))));
1825 return range_typeid;
1828 /* if we return ANYELEMENT use the appropriate argument type */
1829 if (rettype == ANYELEMENTOID ||
1830 rettype == ANYNONARRAYOID ||
1831 rettype == ANYENUMOID)
1834 /* we don't return a generic type; send back the original return type */
1839 * resolve_generic_type()
1840 * Deduce an individual actual datatype on the assumption that
1841 * the rules for polymorphic types are being followed.
1843 * declared_type is the declared datatype we want to resolve.
1844 * context_actual_type is the actual input datatype to some argument
1845 * that has declared datatype context_declared_type.
1847 * If declared_type isn't polymorphic, we just return it. Otherwise,
1848 * context_declared_type must be polymorphic, and we deduce the correct
1849 * return type based on the relationship of the two polymorphic types.
1852 resolve_generic_type(Oid declared_type,
1853 Oid context_actual_type,
1854 Oid context_declared_type)
1856 if (declared_type == ANYARRAYOID)
1858 if (context_declared_type == ANYARRAYOID)
1861 * Use actual type, but it must be an array; or if it's a domain
1862 * over array, use the base array type.
1864 Oid context_base_type = getBaseType(context_actual_type);
1865 Oid array_typelem = get_element_type(context_base_type);
1867 if (!OidIsValid(array_typelem))
1869 (errcode(ERRCODE_DATATYPE_MISMATCH),
1870 errmsg("argument declared \"anyarray\" is not an array but type %s",
1871 format_type_be(context_base_type))));
1872 return context_base_type;
1874 else if (context_declared_type == ANYELEMENTOID ||
1875 context_declared_type == ANYNONARRAYOID ||
1876 context_declared_type == ANYENUMOID ||
1877 context_declared_type == ANYRANGEOID)
1879 /* Use the array type corresponding to actual type */
1880 Oid array_typeid = get_array_type(context_actual_type);
1882 if (!OidIsValid(array_typeid))
1884 (errcode(ERRCODE_UNDEFINED_OBJECT),
1885 errmsg("could not find array type for data type %s",
1886 format_type_be(context_actual_type))));
1887 return array_typeid;
1890 else if (declared_type == ANYELEMENTOID ||
1891 declared_type == ANYNONARRAYOID ||
1892 declared_type == ANYENUMOID ||
1893 declared_type == ANYRANGEOID)
1895 if (context_declared_type == ANYARRAYOID)
1897 /* Use the element type corresponding to actual type */
1898 Oid context_base_type = getBaseType(context_actual_type);
1899 Oid array_typelem = get_element_type(context_base_type);
1901 if (!OidIsValid(array_typelem))
1903 (errcode(ERRCODE_DATATYPE_MISMATCH),
1904 errmsg("argument declared \"anyarray\" is not an array but type %s",
1905 format_type_be(context_base_type))));
1906 return array_typelem;
1908 else if (context_declared_type == ANYRANGEOID)
1910 /* Use the element type corresponding to actual type */
1911 Oid context_base_type = getBaseType(context_actual_type);
1912 Oid range_typelem = get_range_subtype(context_base_type);
1914 if (!OidIsValid(range_typelem))
1916 (errcode(ERRCODE_DATATYPE_MISMATCH),
1917 errmsg("argument declared \"anyrange\" is not a range but type %s",
1918 format_type_be(context_base_type))));
1919 return range_typelem;
1921 else if (context_declared_type == ANYELEMENTOID ||
1922 context_declared_type == ANYNONARRAYOID ||
1923 context_declared_type == ANYENUMOID)
1925 /* Use the actual type; it doesn't matter if array or not */
1926 return context_actual_type;
1931 /* declared_type isn't polymorphic, so return it as-is */
1932 return declared_type;
1934 /* If we get here, declared_type is polymorphic and context isn't */
1935 /* NB: this is a calling-code logic error, not a user error */
1936 elog(ERROR, "could not determine polymorphic type because context isn't polymorphic");
1937 return InvalidOid; /* keep compiler quiet */
1942 * Assign a category to the specified type OID.
1944 * NB: this must not return TYPCATEGORY_INVALID.
1947 TypeCategory(Oid type)
1950 bool typispreferred;
1952 get_type_category_preferred(type, &typcategory, &typispreferred);
1953 Assert(typcategory != TYPCATEGORY_INVALID);
1954 return (TYPCATEGORY) typcategory;
1958 /* IsPreferredType()
1959 * Check if this type is a preferred type for the given category.
1961 * If category is TYPCATEGORY_INVALID, then we'll return TRUE for preferred
1962 * types of any category; otherwise, only for preferred types of that
1966 IsPreferredType(TYPCATEGORY category, Oid type)
1969 bool typispreferred;
1971 get_type_category_preferred(type, &typcategory, &typispreferred);
1972 if (category == typcategory || category == TYPCATEGORY_INVALID)
1973 return typispreferred;
1979 /* IsBinaryCoercible()
1980 * Check if srctype is binary-coercible to targettype.
1982 * This notion allows us to cheat and directly exchange values without
1983 * going through the trouble of calling a conversion function. Note that
1984 * in general, this should only be an implementation shortcut. Before 7.4,
1985 * this was also used as a heuristic for resolving overloaded functions and
1986 * operators, but that's basically a bad idea.
1988 * As of 7.3, binary coercibility isn't hardwired into the code anymore.
1989 * We consider two types binary-coercible if there is an implicitly
1990 * invokable, no-function-needed pg_cast entry. Also, a domain is always
1991 * binary-coercible to its base type, though *not* vice versa (in the other
1992 * direction, one must apply domain constraint checks before accepting the
1993 * value as legitimate). We also need to special-case various polymorphic
1996 * This function replaces IsBinaryCompatible(), which was an inherently
1997 * symmetric test. Since the pg_cast entries aren't necessarily symmetric,
1998 * the order of the operands is now significant.
2001 IsBinaryCoercible(Oid srctype, Oid targettype)
2004 Form_pg_cast castForm;
2007 /* Fast path if same type */
2008 if (srctype == targettype)
2011 /* If srctype is a domain, reduce to its base type */
2012 if (OidIsValid(srctype))
2013 srctype = getBaseType(srctype);
2015 /* Somewhat-fast path for domain -> base type case */
2016 if (srctype == targettype)
2019 /* Also accept any array type as coercible to ANYARRAY */
2020 if (targettype == ANYARRAYOID)
2021 if (type_is_array(srctype))
2024 /* Also accept any non-array type as coercible to ANYNONARRAY */
2025 if (targettype == ANYNONARRAYOID)
2026 if (!type_is_array(srctype))
2029 /* Also accept any enum type as coercible to ANYENUM */
2030 if (targettype == ANYENUMOID)
2031 if (type_is_enum(srctype))
2034 /* Also accept any range type as coercible to ANYRANGE */
2035 if (targettype == ANYRANGEOID)
2036 if (type_is_range(srctype))
2039 /* Also accept any composite type as coercible to RECORD */
2040 if (targettype == RECORDOID)
2041 if (ISCOMPLEX(srctype))
2044 /* Also accept any composite array type as coercible to RECORD[] */
2045 if (targettype == RECORDARRAYOID)
2046 if (is_complex_array(srctype))
2049 /* Else look in pg_cast */
2050 tuple = SearchSysCache2(CASTSOURCETARGET,
2051 ObjectIdGetDatum(srctype),
2052 ObjectIdGetDatum(targettype));
2053 if (!HeapTupleIsValid(tuple))
2054 return false; /* no cast */
2055 castForm = (Form_pg_cast) GETSTRUCT(tuple);
2057 result = (castForm->castmethod == COERCION_METHOD_BINARY &&
2058 castForm->castcontext == COERCION_CODE_IMPLICIT);
2060 ReleaseSysCache(tuple);
2067 * find_coercion_pathway
2068 * Look for a coercion pathway between two types.
2070 * Currently, this deals only with scalar-type cases; it does not consider
2071 * polymorphic types nor casts between composite types. (Perhaps fold
2072 * those in someday?)
2074 * ccontext determines the set of available casts.
2076 * The possible result codes are:
2077 * COERCION_PATH_NONE: failed to find any coercion pathway
2078 * *funcid is set to InvalidOid
2079 * COERCION_PATH_FUNC: apply the coercion function returned in *funcid
2080 * COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
2081 * *funcid is set to InvalidOid
2082 * COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
2083 * *funcid is set to the element cast function, or InvalidOid
2084 * if the array elements are binary-compatible
2085 * COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
2086 * *funcid is set to InvalidOid
2088 * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
2089 * needed to do the coercion; if the target is a domain then we may need to
2090 * apply domain constraint checking. If you want to check for a zero-effort
2091 * conversion then use IsBinaryCoercible().
2094 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
2095 CoercionContext ccontext,
2098 CoercionPathType result = COERCION_PATH_NONE;
2101 *funcid = InvalidOid;
2103 /* Perhaps the types are domains; if so, look at their base types */
2104 if (OidIsValid(sourceTypeId))
2105 sourceTypeId = getBaseType(sourceTypeId);
2106 if (OidIsValid(targetTypeId))
2107 targetTypeId = getBaseType(targetTypeId);
2109 /* Domains are always coercible to and from their base type */
2110 if (sourceTypeId == targetTypeId)
2111 return COERCION_PATH_RELABELTYPE;
2113 /* Look in pg_cast */
2114 tuple = SearchSysCache2(CASTSOURCETARGET,
2115 ObjectIdGetDatum(sourceTypeId),
2116 ObjectIdGetDatum(targetTypeId));
2118 if (HeapTupleIsValid(tuple))
2120 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2121 CoercionContext castcontext;
2123 /* convert char value for castcontext to CoercionContext enum */
2124 switch (castForm->castcontext)
2126 case COERCION_CODE_IMPLICIT:
2127 castcontext = COERCION_IMPLICIT;
2129 case COERCION_CODE_ASSIGNMENT:
2130 castcontext = COERCION_ASSIGNMENT;
2132 case COERCION_CODE_EXPLICIT:
2133 castcontext = COERCION_EXPLICIT;
2136 elog(ERROR, "unrecognized castcontext: %d",
2137 (int) castForm->castcontext);
2138 castcontext = 0; /* keep compiler quiet */
2142 /* Rely on ordering of enum for correct behavior here */
2143 if (ccontext >= castcontext)
2145 switch (castForm->castmethod)
2147 case COERCION_METHOD_FUNCTION:
2148 result = COERCION_PATH_FUNC;
2149 *funcid = castForm->castfunc;
2151 case COERCION_METHOD_INOUT:
2152 result = COERCION_PATH_COERCEVIAIO;
2154 case COERCION_METHOD_BINARY:
2155 result = COERCION_PATH_RELABELTYPE;
2158 elog(ERROR, "unrecognized castmethod: %d",
2159 (int) castForm->castmethod);
2164 ReleaseSysCache(tuple);
2169 * If there's no pg_cast entry, perhaps we are dealing with a pair of
2170 * array types. If so, and if the element types have a suitable cast,
2171 * report that we can coerce with an ArrayCoerceExpr.
2173 * Note that the source type can be a domain over array, but not the
2174 * target, because ArrayCoerceExpr won't check domain constraints.
2176 * Hack: disallow coercions to oidvector and int2vector, which
2177 * otherwise tend to capture coercions that should go to "real" array
2178 * types. We want those types to be considered "real" arrays for many
2179 * purposes, but not this one. (Also, ArrayCoerceExpr isn't
2180 * guaranteed to produce an output that meets the restrictions of
2181 * these datatypes, such as being 1-dimensional.)
2183 if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
2188 if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
2189 (sourceElem = get_base_element_type(sourceTypeId)) != InvalidOid)
2191 CoercionPathType elempathtype;
2194 elempathtype = find_coercion_pathway(targetElem,
2198 if (elempathtype != COERCION_PATH_NONE &&
2199 elempathtype != COERCION_PATH_ARRAYCOERCE)
2201 *funcid = elemfuncid;
2202 if (elempathtype == COERCION_PATH_COERCEVIAIO)
2203 result = COERCION_PATH_COERCEVIAIO;
2205 result = COERCION_PATH_ARRAYCOERCE;
2211 * If we still haven't found a possibility, consider automatic casting
2212 * using I/O functions. We allow assignment casts to string types and
2213 * explicit casts from string types to be handled this way. (The
2214 * CoerceViaIO mechanism is a lot more general than that, but this is
2215 * all we want to allow in the absence of a pg_cast entry.) It would
2216 * probably be better to insist on explicit casts in both directions,
2217 * but this is a compromise to preserve something of the pre-8.3
2218 * behavior that many types had implicit (yipes!) casts to text.
2220 if (result == COERCION_PATH_NONE)
2222 if (ccontext >= COERCION_ASSIGNMENT &&
2223 TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
2224 result = COERCION_PATH_COERCEVIAIO;
2225 else if (ccontext >= COERCION_EXPLICIT &&
2226 TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
2227 result = COERCION_PATH_COERCEVIAIO;
2236 * find_typmod_coercion_function -- does the given type need length coercion?
2238 * If the target type possesses a pg_cast function from itself to itself,
2239 * it must need length coercion.
2241 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
2243 * If the given type is a varlena array type, we do not look for a coercion
2244 * function associated directly with the array type, but instead look for
2245 * one associated with the element type. An ArrayCoerceExpr node must be
2246 * used to apply such a function.
2248 * We use the same result enum as find_coercion_pathway, but the only possible
2250 * COERCION_PATH_NONE: no length coercion needed
2251 * COERCION_PATH_FUNC: apply the function returned in *funcid
2252 * COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
2255 find_typmod_coercion_function(Oid typeId,
2258 CoercionPathType result;
2260 Form_pg_type typeForm;
2263 *funcid = InvalidOid;
2264 result = COERCION_PATH_FUNC;
2266 targetType = typeidType(typeId);
2267 typeForm = (Form_pg_type) GETSTRUCT(targetType);
2269 /* Check for a varlena array type */
2270 if (typeForm->typelem != InvalidOid && typeForm->typlen == -1)
2272 /* Yes, switch our attention to the element type */
2273 typeId = typeForm->typelem;
2274 result = COERCION_PATH_ARRAYCOERCE;
2276 ReleaseSysCache(targetType);
2278 /* Look in pg_cast */
2279 tuple = SearchSysCache2(CASTSOURCETARGET,
2280 ObjectIdGetDatum(typeId),
2281 ObjectIdGetDatum(typeId));
2283 if (HeapTupleIsValid(tuple))
2285 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2287 *funcid = castForm->castfunc;
2288 ReleaseSysCache(tuple);
2291 if (!OidIsValid(*funcid))
2292 result = COERCION_PATH_NONE;
2299 * Is this type an array of composite?
2301 * Note: this will not return true for record[]; check for RECORDARRAYOID
2302 * separately if needed.
2305 is_complex_array(Oid typid)
2307 Oid elemtype = get_element_type(typid);
2309 return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));
2314 * Check whether reltypeId is the row type of a typed table of type
2315 * reloftypeId. (This is conceptually similar to the subtype
2316 * relationship checked by typeInheritsFrom().)
2319 typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
2321 Oid relid = typeidTypeRelid(reltypeId);
2322 bool result = false;
2327 Form_pg_class reltup;
2329 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2330 if (!HeapTupleIsValid(tp))
2331 elog(ERROR, "cache lookup failed for relation %u", relid);
2333 reltup = (Form_pg_class) GETSTRUCT(tp);
2334 if (reltup->reloftype == reloftypeId)
2337 ReleaseSysCache(tp);