1 /*-------------------------------------------------------------------------
4 * handle type coercions/conversions for parser
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/parser/parse_coerce.c,v 2.174 2009/01/01 17:23:45 momjian Exp $
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_cast.h"
18 #include "catalog/pg_proc.h"
19 #include "catalog/pg_type.h"
20 #include "nodes/makefuncs.h"
21 #include "nodes/nodeFuncs.h"
22 #include "parser/parse_coerce.h"
23 #include "parser/parse_func.h"
24 #include "parser/parse_relation.h"
25 #include "parser/parse_type.h"
26 #include "utils/builtins.h"
27 #include "utils/fmgroids.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);
53 * coerce_to_target_type()
54 * Convert an expression to a target type and typmod.
56 * This is the general-purpose entry point for arbitrary type coercion
57 * operations. Direct use of the component operations can_coerce_type,
58 * coerce_type, and coerce_type_typmod should be restricted to special
59 * cases (eg, when the conversion is expected to succeed).
61 * Returns the possibly-transformed expression tree, or NULL if the type
62 * conversion is not possible. (We do this, rather than ereport'ing directly,
63 * so that callers can generate custom error messages indicating context.)
65 * pstate - parse state (can be NULL, see coerce_type)
66 * expr - input expression tree (already transformed by transformExpr)
67 * exprtype - result type of expr
68 * targettype - desired result type
69 * targettypmod - desired result typmod
70 * ccontext, cformat - context indicators to control coercions
71 * location - parse location of the coercion request, or -1 if unknown/implicit
74 coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype,
75 Oid targettype, int32 targettypmod,
76 CoercionContext ccontext,
82 if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
85 result = coerce_type(pstate, expr, exprtype,
86 targettype, targettypmod,
87 ccontext, cformat, location);
90 * If the target is a fixed-length type, it may need a length coercion as
91 * well as a type coercion. If we find ourselves adding both, force the
92 * inner coercion node to implicit display form.
94 result = coerce_type_typmod(result,
95 targettype, targettypmod,
97 (cformat != COERCE_IMPLICIT_CAST),
98 (result != expr && !IsA(result, Const)));
106 * Convert an expression to a different type.
108 * The caller should already have determined that the coercion is possible;
109 * see can_coerce_type.
111 * Normally, no coercion to a typmod (length) is performed here. The caller
112 * must call coerce_type_typmod as well, if a typmod constraint is wanted.
113 * (But if the target type is a domain, it may internally contain a
114 * typmod constraint, which will be applied inside coerce_to_domain.)
115 * In some cases pg_cast specifies a type coercion function that also
116 * applies length conversion, and in those cases only, the result will
117 * already be properly coerced to the specified typmod.
119 * pstate is only used in the case that we are able to resolve the type of
120 * a previously UNKNOWN Param. It is okay to pass pstate = NULL if the
121 * caller does not want type information updated for Params.
124 coerce_type(ParseState *pstate, Node *node,
125 Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
126 CoercionContext ccontext, CoercionForm cformat, int location)
129 CoercionPathType pathtype;
132 if (targetTypeId == inputTypeId ||
135 /* no conversion needed */
138 if (targetTypeId == ANYOID ||
139 targetTypeId == ANYELEMENTOID ||
140 targetTypeId == ANYNONARRAYOID ||
141 (targetTypeId == ANYARRAYOID && inputTypeId != UNKNOWNOID) ||
142 (targetTypeId == ANYENUMOID && inputTypeId != UNKNOWNOID))
145 * Assume can_coerce_type verified that implicit coercion is okay.
147 * Note: by returning the unmodified node here, we are saying that
148 * it's OK to treat an UNKNOWN constant as a valid input for a
149 * function accepting ANY, ANYELEMENT, or ANYNONARRAY. This should be
150 * all right, since an UNKNOWN value is still a perfectly valid Datum.
151 * However an UNKNOWN value is definitely *not* an array, and so we
152 * mustn't accept it for ANYARRAY. (Instead, we will call anyarray_in
153 * below, which will produce an error.) Likewise, UNKNOWN input is no
156 * NB: we do NOT want a RelabelType here.
160 if (inputTypeId == UNKNOWNOID && IsA(node, Const))
163 * Input is a string constant with previously undetermined type. Apply
164 * the target type's typinput function to it to produce a constant of
167 * NOTE: this case cannot be folded together with the other
168 * constant-input case, since the typinput function does not
169 * necessarily behave the same as a type conversion function. For
170 * example, int4's typinput function will reject "1.2", whereas
171 * float-to-int type conversion will round to integer.
173 * XXX if the typinput function is not immutable, we really ought to
174 * postpone evaluation of the function call until runtime. But there
175 * is no way to represent a typinput function call as an expression
176 * tree, because C-string values are not Datums. (XXX This *is*
177 * possible as of 7.3, do we want to do it?)
179 Const *con = (Const *) node;
180 Const *newcon = makeNode(Const);
185 ParseCallbackState pcbstate;
188 * If the target type is a domain, we want to call its base type's
189 * input routine, not domain_in(). This is to avoid premature failure
190 * when the domain applies a typmod: existing input routines follow
191 * implicit-coercion semantics for length checks, which is not always
192 * what we want here. The needed check will be applied properly
193 * inside coerce_to_domain().
195 baseTypeMod = targetTypeMod;
196 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
199 * For most types we pass typmod -1 to the input routine, because
200 * existing input routines follow implicit-coercion semantics for
201 * length checks, which is not always what we want here. Any length
202 * constraint will be applied later by our caller. An exception
203 * however is the INTERVAL type, for which we *must* pass the typmod
204 * or it won't be able to obey the bizarre SQL-spec input rules.
205 * (Ugly as sin, but so is this part of the spec...)
207 if (baseTypeId == INTERVALOID)
208 inputTypeMod = baseTypeMod;
212 targetType = typeidType(baseTypeId);
214 newcon->consttype = baseTypeId;
215 newcon->consttypmod = inputTypeMod;
216 newcon->constlen = typeLen(targetType);
217 newcon->constbyval = typeByVal(targetType);
218 newcon->constisnull = con->constisnull;
219 /* Use the leftmost of the constant's and coercion's locations */
221 newcon->location = con->location;
222 else if (con->location >= 0 && con->location < location)
223 newcon->location = con->location;
225 newcon->location = location;
228 * Set up to point at the constant's text if the input routine
231 setup_parser_errposition_callback(&pcbstate, pstate, con->location);
234 * We assume here that UNKNOWN's internal representation is the same
237 if (!con->constisnull)
238 newcon->constvalue = stringTypeDatum(targetType,
239 DatumGetCString(con->constvalue),
242 newcon->constvalue = stringTypeDatum(targetType,
246 cancel_parser_errposition_callback(&pcbstate);
248 result = (Node *) newcon;
250 /* If target is a domain, apply constraints. */
251 if (baseTypeId != targetTypeId)
252 result = coerce_to_domain(result,
253 baseTypeId, baseTypeMod,
255 cformat, location, false, false);
257 ReleaseSysCache(targetType);
261 if (inputTypeId == UNKNOWNOID && IsA(node, Param) &&
262 ((Param *) node)->paramkind == PARAM_EXTERN &&
263 pstate != NULL && pstate->p_variableparams)
266 * Input is a Param of previously undetermined type, and we want to
267 * update our knowledge of the Param's type. Find the topmost
268 * ParseState and update the state.
270 Param *param = (Param *) node;
271 int paramno = param->paramid;
272 ParseState *toppstate;
275 while (toppstate->parentParseState != NULL)
276 toppstate = toppstate->parentParseState;
278 if (paramno <= 0 || /* shouldn't happen, but... */
279 paramno > toppstate->p_numparams)
281 (errcode(ERRCODE_UNDEFINED_PARAMETER),
282 errmsg("there is no parameter $%d", paramno),
283 parser_errposition(pstate, param->location)));
285 if (toppstate->p_paramtypes[paramno - 1] == UNKNOWNOID)
287 /* We've successfully resolved the type */
288 toppstate->p_paramtypes[paramno - 1] = targetTypeId;
290 else if (toppstate->p_paramtypes[paramno - 1] == targetTypeId)
292 /* We previously resolved the type, and it matches */
298 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
299 errmsg("inconsistent types deduced for parameter $%d",
301 errdetail("%s versus %s",
302 format_type_be(toppstate->p_paramtypes[paramno - 1]),
303 format_type_be(targetTypeId)),
304 parser_errposition(pstate, param->location)));
307 param->paramtype = targetTypeId;
310 * Note: it is tempting here to set the Param's paramtypmod to
311 * targetTypeMod, but that is probably unwise because we have no
312 * infrastructure that enforces that the value delivered for a Param
313 * will match any particular typmod. Leaving it -1 ensures that a
314 * run-time length check/coercion will occur if needed.
316 param->paramtypmod = -1;
318 /* Use the leftmost of the param's and coercion's locations */
320 (param->location < 0 || location < param->location))
321 param->location = location;
323 return (Node *) param;
325 pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
327 if (pathtype != COERCION_PATH_NONE)
329 if (pathtype != COERCION_PATH_RELABELTYPE)
332 * Generate an expression tree representing run-time application
333 * of the conversion function. If we are dealing with a domain
334 * target type, the conversion function will yield the base type,
335 * and we need to extract the correct typmod to use from the
336 * domain's typtypmod.
341 baseTypeMod = targetTypeMod;
342 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
344 result = build_coercion_expression(node, pathtype, funcId,
345 baseTypeId, baseTypeMod,
347 (cformat != COERCE_IMPLICIT_CAST));
350 * If domain, coerce to the domain type and relabel with domain
351 * type ID. We can skip the internal length-coercion step if the
352 * selected coercion function was a type-and-length coercion.
354 if (targetTypeId != baseTypeId)
355 result = coerce_to_domain(result, baseTypeId, baseTypeMod,
357 cformat, location, true,
358 exprIsLengthCoercion(result,
364 * We don't need to do a physical conversion, but we do need to
365 * attach a RelabelType node so that the expression will be seen
366 * to have the intended type when inspected by higher-level code.
368 * Also, domains may have value restrictions beyond the base type
369 * that must be accounted for. If the destination is a domain
370 * then we won't need a RelabelType node.
372 result = coerce_to_domain(node, InvalidOid, -1, targetTypeId,
373 cformat, location, false, false);
377 * XXX could we label result with exprTypmod(node) instead of
378 * default -1 typmod, to save a possible length-coercion
379 * later? Would work if both types have same interpretation of
380 * typmod, which is likely but not certain.
382 RelabelType *r = makeRelabelType((Expr *) result,
386 r->location = location;
392 if (inputTypeId == RECORDOID &&
393 ISCOMPLEX(targetTypeId))
395 /* Coerce a RECORD to a specific complex type */
396 return coerce_record_to_complex(pstate, node, targetTypeId,
397 ccontext, cformat, location);
399 if (targetTypeId == RECORDOID &&
400 ISCOMPLEX(inputTypeId))
402 /* Coerce a specific complex type to RECORD */
403 /* NB: we do NOT want a RelabelType here */
407 if (inputTypeId == RECORDARRAYOID &&
408 is_complex_array(targetTypeId))
410 /* Coerce record[] to a specific complex array type */
411 /* not implemented yet ... */
414 if (targetTypeId == RECORDARRAYOID &&
415 is_complex_array(inputTypeId))
417 /* Coerce a specific complex array type to record[] */
418 /* NB: we do NOT want a RelabelType here */
421 if (typeInheritsFrom(inputTypeId, targetTypeId))
424 * Input class type is a subclass of target, so generate an
425 * appropriate runtime conversion (removing unneeded columns and
426 * possibly rearranging the ones that are wanted).
428 ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
430 r->arg = (Expr *) node;
431 r->resulttype = targetTypeId;
432 r->convertformat = cformat;
433 r->location = location;
436 /* If we get here, caller blew it */
437 elog(ERROR, "failed to find conversion function from %s to %s",
438 format_type_be(inputTypeId), format_type_be(targetTypeId));
439 return NULL; /* keep compiler quiet */
445 * Can input_typeids be coerced to target_typeids?
447 * We must be told the context (CAST construct, assignment, implicit coercion)
448 * as this determines the set of available casts.
451 can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids,
452 CoercionContext ccontext)
454 bool have_generics = false;
457 /* run through argument list... */
458 for (i = 0; i < nargs; i++)
460 Oid inputTypeId = input_typeids[i];
461 Oid targetTypeId = target_typeids[i];
462 CoercionPathType pathtype;
465 /* no problem if same type */
466 if (inputTypeId == targetTypeId)
469 /* accept if target is ANY */
470 if (targetTypeId == ANYOID)
473 /* accept if target is polymorphic, for now */
474 if (IsPolymorphicType(targetTypeId))
476 have_generics = true; /* do more checking later */
481 * If input is an untyped string constant, assume we can convert it to
484 if (inputTypeId == UNKNOWNOID)
488 * If pg_cast shows that we can coerce, accept. This test now covers
489 * both binary-compatible and coercion-function cases.
491 pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
493 if (pathtype != COERCION_PATH_NONE)
497 * If input is RECORD and target is a composite type, assume we can
498 * coerce (may need tighter checking here)
500 if (inputTypeId == RECORDOID &&
501 ISCOMPLEX(targetTypeId))
505 * If input is a composite type and target is RECORD, accept
507 if (targetTypeId == RECORDOID &&
508 ISCOMPLEX(inputTypeId))
511 #ifdef NOT_USED /* not implemented yet */
513 * If input is record[] and target is a composite array type,
514 * assume we can coerce (may need tighter checking here)
516 if (inputTypeId == RECORDARRAYOID &&
517 is_complex_array(targetTypeId))
522 * If input is a composite array type and target is record[], accept
524 if (targetTypeId == RECORDARRAYOID &&
525 is_complex_array(inputTypeId))
529 * If input is a class type that inherits from target, accept
531 if (typeInheritsFrom(inputTypeId, targetTypeId))
535 * Else, cannot coerce at this argument position
540 /* If we found any generic argument types, cross-check them */
543 if (!check_generic_type_consistency(input_typeids, target_typeids,
553 * Create an expression tree to represent coercion to a domain type.
555 * 'arg': input expression
556 * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
557 * has not bothered to look this up)
558 * 'baseTypeMod': base type typmod of domain, if known (pass -1 if caller
559 * has not bothered to look this up)
560 * 'typeId': target type to coerce to
561 * 'cformat': coercion format
562 * 'location': coercion request location
563 * 'hideInputCoercion': if true, hide the input coercion under this one.
564 * 'lengthCoercionDone': if true, caller already accounted for length,
565 * ie the input is already of baseTypMod as well as baseTypeId.
567 * If the target type isn't a domain, the given 'arg' is returned as-is.
570 coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId,
571 CoercionForm cformat, int location,
572 bool hideInputCoercion,
573 bool lengthCoercionDone)
575 CoerceToDomain *result;
577 /* Get the base type if it hasn't been supplied */
578 if (baseTypeId == InvalidOid)
579 baseTypeId = getBaseTypeAndTypmod(typeId, &baseTypeMod);
581 /* If it isn't a domain, return the node as it was passed in */
582 if (baseTypeId == typeId)
585 /* Suppress display of nested coercion steps */
586 if (hideInputCoercion)
587 hide_coercion_node(arg);
590 * If the domain applies a typmod to its base type, build the appropriate
591 * coercion step. Mark it implicit for display purposes, because we don't
592 * want it shown separately by ruleutils.c; but the isExplicit flag passed
593 * to the conversion function depends on the manner in which the domain
594 * coercion is invoked, so that the semantics of implicit and explicit
595 * coercion differ. (Is that really the behavior we want?)
597 * NOTE: because we apply this as part of the fixed expression structure,
598 * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that that
599 * would be safe to do anyway, without lots of knowledge about what the
600 * base type thinks the typmod means.
602 if (!lengthCoercionDone)
604 if (baseTypeMod >= 0)
605 arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
606 COERCE_IMPLICIT_CAST, location,
607 (cformat != COERCE_IMPLICIT_CAST),
612 * Now build the domain coercion node. This represents run-time checking
613 * of any constraints currently attached to the domain. This also ensures
614 * that the expression is properly labeled as to result type.
616 result = makeNode(CoerceToDomain);
617 result->arg = (Expr *) arg;
618 result->resulttype = typeId;
619 result->resulttypmod = -1; /* currently, always -1 for domains */
620 result->coercionformat = cformat;
621 result->location = location;
623 return (Node *) result;
628 * coerce_type_typmod()
629 * Force a value to a particular typmod, if meaningful and possible.
631 * This is applied to values that are going to be stored in a relation
632 * (where we have an atttypmod for the column) as well as values being
633 * explicitly CASTed (where the typmod comes from the target type spec).
635 * The caller must have already ensured that the value is of the correct
636 * type, typically by applying coerce_type.
638 * cformat determines the display properties of the generated node (if any),
639 * while isExplicit may affect semantics. If hideInputCoercion is true
640 * *and* we generate a node, the input node is forced to IMPLICIT display
641 * form, so that only the typmod coercion node will be visible when
642 * displaying the expression.
644 * NOTE: this does not need to work on domain types, because any typmod
645 * coercion for a domain is considered to be part of the type coercion
646 * needed to produce the domain value in the first place. So, no getBaseType.
649 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
650 CoercionForm cformat, int location,
651 bool isExplicit, bool hideInputCoercion)
653 CoercionPathType pathtype;
657 * A negative typmod is assumed to mean that no coercion is wanted. Also,
658 * skip coercion if already done.
660 if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
663 pathtype = find_typmod_coercion_function(targetTypeId, &funcId);
665 if (pathtype != COERCION_PATH_NONE)
667 /* Suppress display of nested coercion steps */
668 if (hideInputCoercion)
669 hide_coercion_node(node);
671 node = build_coercion_expression(node, pathtype, funcId,
672 targetTypeId, targetTypMod,
681 * Mark a coercion node as IMPLICIT so it will never be displayed by
682 * ruleutils.c. We use this when we generate a nest of coercion nodes
683 * to implement what is logically one conversion; the inner nodes are
684 * forced to IMPLICIT_CAST format. This does not change their semantics,
685 * only display behavior.
687 * It is caller error to call this on something that doesn't have a
688 * CoercionForm field.
691 hide_coercion_node(Node *node)
693 if (IsA(node, FuncExpr))
694 ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
695 else if (IsA(node, RelabelType))
696 ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
697 else if (IsA(node, CoerceViaIO))
698 ((CoerceViaIO *) node)->coerceformat = COERCE_IMPLICIT_CAST;
699 else if (IsA(node, ArrayCoerceExpr))
700 ((ArrayCoerceExpr *) node)->coerceformat = COERCE_IMPLICIT_CAST;
701 else if (IsA(node, ConvertRowtypeExpr))
702 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
703 else if (IsA(node, RowExpr))
704 ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
705 else if (IsA(node, CoerceToDomain))
706 ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
708 elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
712 * build_coercion_expression()
713 * Construct an expression tree for applying a pg_cast entry.
715 * This is used for both type-coercion and length-coercion operations,
716 * since there is no difference in terms of the calling convention.
719 build_coercion_expression(Node *node,
720 CoercionPathType pathtype,
722 Oid targetTypeId, int32 targetTypMod,
723 CoercionForm cformat, int location,
728 if (OidIsValid(funcId))
731 Form_pg_proc procstruct;
733 tp = SearchSysCache(PROCOID,
734 ObjectIdGetDatum(funcId),
736 if (!HeapTupleIsValid(tp))
737 elog(ERROR, "cache lookup failed for function %u", funcId);
738 procstruct = (Form_pg_proc) GETSTRUCT(tp);
741 * These Asserts essentially check that function is a legal coercion
742 * function. We can't make the seemingly obvious tests on prorettype
743 * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
744 * various binary-compatibility cases.
746 /* Assert(targetTypeId == procstruct->prorettype); */
747 Assert(!procstruct->proretset);
748 Assert(!procstruct->proisagg);
749 Assert(!procstruct->proiswindow);
750 nargs = procstruct->pronargs;
751 Assert(nargs >= 1 && nargs <= 3);
752 /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
753 Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
754 Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
759 if (pathtype == COERCION_PATH_FUNC)
761 /* We build an ordinary FuncExpr with special arguments */
766 Assert(OidIsValid(funcId));
768 args = list_make1(node);
772 /* Pass target typmod as an int4 constant */
773 cons = makeConst(INT4OID,
776 Int32GetDatum(targetTypMod),
780 args = lappend(args, cons);
785 /* Pass it a boolean isExplicit parameter, too */
786 cons = makeConst(BOOLOID,
789 BoolGetDatum(isExplicit),
793 args = lappend(args, cons);
796 fexpr = makeFuncExpr(funcId, targetTypeId, args, cformat);
797 fexpr->location = location;
798 return (Node *) fexpr;
800 else if (pathtype == COERCION_PATH_ARRAYCOERCE)
802 /* We need to build an ArrayCoerceExpr */
803 ArrayCoerceExpr *acoerce = makeNode(ArrayCoerceExpr);
805 acoerce->arg = (Expr *) node;
806 acoerce->elemfuncid = funcId;
807 acoerce->resulttype = targetTypeId;
810 * Label the output as having a particular typmod only if we are
811 * really invoking a length-coercion function, ie one with more than
814 acoerce->resulttypmod = (nargs >= 2) ? targetTypMod : -1;
815 acoerce->isExplicit = isExplicit;
816 acoerce->coerceformat = cformat;
817 acoerce->location = location;
819 return (Node *) acoerce;
821 else if (pathtype == COERCION_PATH_COERCEVIAIO)
823 /* We need to build a CoerceViaIO node */
824 CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
826 Assert(!OidIsValid(funcId));
828 iocoerce->arg = (Expr *) node;
829 iocoerce->resulttype = targetTypeId;
830 iocoerce->coerceformat = cformat;
831 iocoerce->location = location;
833 return (Node *) iocoerce;
837 elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
839 return NULL; /* keep compiler quiet */
845 * coerce_record_to_complex
846 * Coerce a RECORD to a specific composite type.
848 * Currently we only support this for inputs that are RowExprs or whole-row
852 coerce_record_to_complex(ParseState *pstate, Node *node,
854 CoercionContext ccontext,
855 CoercionForm cformat,
866 if (node && IsA(node, RowExpr))
869 * Since the RowExpr must be of type RECORD, we needn't worry about it
870 * containing any dropped columns.
872 args = ((RowExpr *) node)->args;
874 else if (node && IsA(node, Var) &&
875 ((Var *) node)->varattno == InvalidAttrNumber)
877 int rtindex = ((Var *) node)->varno;
878 int sublevels_up = ((Var *) node)->varlevelsup;
879 int vlocation = ((Var *) node)->location;
882 rte = GetRTEByRangeTablePosn(pstate, rtindex, sublevels_up);
883 expandRTE(rte, rtindex, sublevels_up, vlocation, false,
888 (errcode(ERRCODE_CANNOT_COERCE),
889 errmsg("cannot cast type %s to %s",
890 format_type_be(RECORDOID),
891 format_type_be(targetTypeId)),
892 parser_coercion_errposition(pstate, location, node)));
894 tupdesc = lookup_rowtype_tupdesc(targetTypeId, -1);
897 arg = list_head(args);
898 for (i = 0; i < tupdesc->natts; i++)
904 /* Fill in NULLs for dropped columns in rowtype */
905 if (tupdesc->attrs[i]->attisdropped)
908 * can't use atttypid here, but it doesn't really matter what type
909 * the Const claims to be.
911 newargs = lappend(newargs, makeNullConst(INT4OID, -1));
917 (errcode(ERRCODE_CANNOT_COERCE),
918 errmsg("cannot cast type %s to %s",
919 format_type_be(RECORDOID),
920 format_type_be(targetTypeId)),
921 errdetail("Input has too few columns."),
922 parser_coercion_errposition(pstate, location, node)));
923 expr = (Node *) lfirst(arg);
924 exprtype = exprType(expr);
926 cexpr = coerce_to_target_type(pstate,
928 tupdesc->attrs[i]->atttypid,
929 tupdesc->attrs[i]->atttypmod,
931 COERCE_IMPLICIT_CAST,
935 (errcode(ERRCODE_CANNOT_COERCE),
936 errmsg("cannot cast type %s to %s",
937 format_type_be(RECORDOID),
938 format_type_be(targetTypeId)),
939 errdetail("Cannot cast type %s to %s in column %d.",
940 format_type_be(exprtype),
941 format_type_be(tupdesc->attrs[i]->atttypid),
943 parser_coercion_errposition(pstate, location, expr)));
944 newargs = lappend(newargs, cexpr);
950 (errcode(ERRCODE_CANNOT_COERCE),
951 errmsg("cannot cast type %s to %s",
952 format_type_be(RECORDOID),
953 format_type_be(targetTypeId)),
954 errdetail("Input has too many columns."),
955 parser_coercion_errposition(pstate, location, node)));
957 ReleaseTupleDesc(tupdesc);
959 rowexpr = makeNode(RowExpr);
960 rowexpr->args = newargs;
961 rowexpr->row_typeid = targetTypeId;
962 rowexpr->row_format = cformat;
963 rowexpr->colnames = NIL; /* not needed for named target type */
964 rowexpr->location = location;
965 return (Node *) rowexpr;
969 * coerce_to_boolean()
970 * Coerce an argument of a construct that requires boolean input
971 * (AND, OR, NOT, etc). Also check that input is not a set.
973 * Returns the possibly-transformed node tree.
975 * As with coerce_type, pstate may be NULL if no special unknown-Param
976 * processing is wanted.
979 coerce_to_boolean(ParseState *pstate, Node *node,
980 const char *constructName)
982 Oid inputTypeId = exprType(node);
984 if (inputTypeId != BOOLOID)
988 newnode = coerce_to_target_type(pstate, node, inputTypeId,
991 COERCE_IMPLICIT_CAST,
995 (errcode(ERRCODE_DATATYPE_MISMATCH),
996 /* translator: first %s is name of a SQL construct, eg WHERE */
997 errmsg("argument of %s must be type boolean, not type %s",
998 constructName, format_type_be(inputTypeId)),
999 parser_errposition(pstate, exprLocation(node))));
1003 if (expression_returns_set(node))
1005 (errcode(ERRCODE_DATATYPE_MISMATCH),
1006 /* translator: %s is name of a SQL construct, eg WHERE */
1007 errmsg("argument of %s must not return a set",
1009 parser_errposition(pstate, exprLocation(node))));
1015 * coerce_to_specific_type()
1016 * Coerce an argument of a construct that requires a specific data type.
1017 * Also check that input is not a set.
1019 * Returns the possibly-transformed node tree.
1021 * As with coerce_type, pstate may be NULL if no special unknown-Param
1022 * processing is wanted.
1025 coerce_to_specific_type(ParseState *pstate, Node *node,
1027 const char *constructName)
1029 Oid inputTypeId = exprType(node);
1031 if (inputTypeId != targetTypeId)
1035 newnode = coerce_to_target_type(pstate, node, inputTypeId,
1037 COERCION_ASSIGNMENT,
1038 COERCE_IMPLICIT_CAST,
1040 if (newnode == NULL)
1042 (errcode(ERRCODE_DATATYPE_MISMATCH),
1043 /* translator: first %s is name of a SQL construct, eg LIMIT */
1044 errmsg("argument of %s must be type %s, not type %s",
1046 format_type_be(targetTypeId),
1047 format_type_be(inputTypeId)),
1048 parser_errposition(pstate, exprLocation(node))));
1052 if (expression_returns_set(node))
1054 (errcode(ERRCODE_DATATYPE_MISMATCH),
1055 /* translator: %s is name of a SQL construct, eg LIMIT */
1056 errmsg("argument of %s must not return a set",
1058 parser_errposition(pstate, exprLocation(node))));
1065 * parser_coercion_errposition - report coercion error location, if possible
1067 * We prefer to point at the coercion request (CAST, ::, etc) if possible;
1068 * but there may be no such location in the case of an implicit coercion.
1069 * In that case point at the input expression.
1071 * XXX possibly this is more generally useful than coercion errors;
1072 * if so, should rename and place with parser_errposition.
1075 parser_coercion_errposition(ParseState *pstate,
1076 int coerce_location,
1079 if (coerce_location >= 0)
1080 return parser_errposition(pstate, coerce_location);
1082 return parser_errposition(pstate, exprLocation(input_expr));
1087 * select_common_type()
1088 * Determine the common supertype of a list of input expressions.
1089 * This is used for determining the output type of CASE, UNION,
1090 * and similar constructs.
1092 * 'exprs' is a *nonempty* list of expressions. Note that earlier items
1093 * in the list will be preferred if there is doubt.
1094 * 'context' is a phrase to use in the error message if we fail to select
1095 * a usable type. Pass NULL to have the routine return InvalidOid
1096 * rather than throwing an error on failure.
1097 * 'which_expr': if not NULL, receives a pointer to the particular input
1098 * expression from which the result type was taken.
1101 select_common_type(ParseState *pstate, List *exprs, const char *context,
1106 TYPCATEGORY pcategory;
1110 Assert(exprs != NIL);
1111 pexpr = (Node *) linitial(exprs);
1112 lc = lnext(list_head(exprs));
1113 ptype = exprType(pexpr);
1116 * If all input types are valid and exactly the same, just pick that type.
1117 * This is the only way that we will resolve the result as being a domain
1118 * type; otherwise domains are smashed to their base types for comparison.
1120 if (ptype != UNKNOWNOID)
1122 for_each_cell(lc, lc)
1124 Node *nexpr = (Node *) lfirst(lc);
1125 Oid ntype = exprType(nexpr);
1130 if (lc == NULL) /* got to the end of the list? */
1133 *which_expr = pexpr;
1139 * Nope, so set up for the full algorithm. Note that at this point,
1140 * lc points to the first list item with type different from pexpr's;
1141 * we need not re-examine any items the previous loop advanced over.
1143 ptype = getBaseType(ptype);
1144 get_type_category_preferred(ptype, &pcategory, &pispreferred);
1146 for_each_cell(lc, lc)
1148 Node *nexpr = (Node *) lfirst(lc);
1149 Oid ntype = getBaseType(exprType(nexpr));
1151 /* move on to next one if no new information... */
1152 if (ntype != UNKNOWNOID && ntype != ptype)
1154 TYPCATEGORY ncategory;
1157 get_type_category_preferred(ntype, &ncategory, &nispreferred);
1158 if (ptype == UNKNOWNOID)
1160 /* so far, only unknowns so take anything... */
1163 pcategory = ncategory;
1164 pispreferred = nispreferred;
1166 else if (ncategory != pcategory)
1169 * both types in different categories? then not much hope...
1171 if (context == NULL)
1174 (errcode(ERRCODE_DATATYPE_MISMATCH),
1176 translator: first %s is name of a SQL construct, eg CASE */
1177 errmsg("%s types %s and %s cannot be matched",
1179 format_type_be(ptype),
1180 format_type_be(ntype)),
1181 parser_errposition(pstate, exprLocation(nexpr))));
1183 else if (!pispreferred &&
1184 can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1185 !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1188 * take new type if can coerce to it implicitly but not the
1189 * other way; but if we have a preferred type, stay on it.
1193 pcategory = ncategory;
1194 pispreferred = nispreferred;
1200 * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1201 * then resolve as type TEXT. This situation comes up with constructs
1202 * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1203 * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1204 * output type as UNKNOWN, but that really doesn't work, because we'd
1205 * probably end up needing a runtime coercion from UNKNOWN to something
1206 * else, and we usually won't have it. We need to coerce the unknown
1207 * literals while they are still literals, so a decision has to be made
1210 if (ptype == UNKNOWNOID)
1214 *which_expr = pexpr;
1219 * coerce_to_common_type()
1220 * Coerce an expression to the given type.
1222 * This is used following select_common_type() to coerce the individual
1223 * expressions to the desired type. 'context' is a phrase to use in the
1224 * error message if we fail to coerce.
1226 * As with coerce_type, pstate may be NULL if no special unknown-Param
1227 * processing is wanted.
1230 coerce_to_common_type(ParseState *pstate, Node *node,
1231 Oid targetTypeId, const char *context)
1233 Oid inputTypeId = exprType(node);
1235 if (inputTypeId == targetTypeId)
1236 return node; /* no work */
1237 if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
1238 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1239 COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
1242 (errcode(ERRCODE_CANNOT_COERCE),
1243 /* translator: first %s is name of a SQL construct, eg CASE */
1244 errmsg("%s could not convert type %s to %s",
1246 format_type_be(inputTypeId),
1247 format_type_be(targetTypeId)),
1248 parser_errposition(pstate, exprLocation(node))));
1253 * check_generic_type_consistency()
1254 * Are the actual arguments potentially compatible with a
1255 * polymorphic function?
1257 * The argument consistency rules are:
1259 * 1) All arguments declared ANYARRAY must have matching datatypes,
1260 * and must in fact be varlena arrays.
1261 * 2) All arguments declared ANYELEMENT must have matching datatypes.
1262 * 3) If there are arguments of both ANYELEMENT and ANYARRAY, make sure
1263 * the actual ANYELEMENT datatype is in fact the element type for
1264 * the actual ANYARRAY datatype.
1265 * 4) ANYENUM is treated the same as ANYELEMENT except that if it is used
1266 * (alone or in combination with plain ANYELEMENT), we add the extra
1267 * condition that the ANYELEMENT type must be an enum.
1268 * 5) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1269 * we add the extra condition that the ANYELEMENT type must not be an array.
1270 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1271 * is an extra restriction if not.)
1273 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1274 * argument, assume it is okay.
1276 * If an input is of type ANYARRAY (ie, we know it's an array, but not
1277 * what element type), we will accept it as a match to an argument declared
1278 * ANYARRAY, so long as we don't have to determine an element type ---
1279 * that is, so long as there is no use of ANYELEMENT. This is mostly for
1280 * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
1282 * We do not ereport here, but just return FALSE if a rule is violated.
1285 check_generic_type_consistency(Oid *actual_arg_types,
1286 Oid *declared_arg_types,
1290 Oid elem_typeid = InvalidOid;
1291 Oid array_typeid = InvalidOid;
1293 bool have_anyelement = false;
1294 bool have_anynonarray = false;
1295 bool have_anyenum = false;
1298 * Loop through the arguments to see if we have any that are polymorphic.
1299 * If so, require the actual types to be consistent.
1301 for (j = 0; j < nargs; j++)
1303 Oid decl_type = declared_arg_types[j];
1304 Oid actual_type = actual_arg_types[j];
1306 if (decl_type == ANYELEMENTOID ||
1307 decl_type == ANYNONARRAYOID ||
1308 decl_type == ANYENUMOID)
1310 have_anyelement = true;
1311 if (decl_type == ANYNONARRAYOID)
1312 have_anynonarray = true;
1313 else if (decl_type == ANYENUMOID)
1314 have_anyenum = true;
1315 if (actual_type == UNKNOWNOID)
1317 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1319 elem_typeid = actual_type;
1321 else if (decl_type == ANYARRAYOID)
1323 if (actual_type == UNKNOWNOID)
1325 if (OidIsValid(array_typeid) && actual_type != array_typeid)
1327 array_typeid = actual_type;
1331 /* Get the element type based on the array type, if we have one */
1332 if (OidIsValid(array_typeid))
1334 if (array_typeid == ANYARRAYOID)
1336 /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1337 if (have_anyelement)
1342 array_typelem = get_element_type(array_typeid);
1343 if (!OidIsValid(array_typelem))
1344 return false; /* should be an array, but isn't */
1346 if (!OidIsValid(elem_typeid))
1349 * if we don't have an element type yet, use the one we just got
1351 elem_typeid = array_typelem;
1353 else if (array_typelem != elem_typeid)
1355 /* otherwise, they better match */
1360 if (have_anynonarray)
1362 /* require the element type to not be an array */
1363 if (type_is_array(elem_typeid))
1369 /* require the element type to be an enum */
1370 if (!type_is_enum(elem_typeid))
1379 * enforce_generic_type_consistency()
1380 * Make sure a polymorphic function is legally callable, and
1381 * deduce actual argument and result types.
1383 * If any polymorphic pseudotype is used in a function's arguments or
1384 * return type, we make sure the actual data types are consistent with
1385 * each other. The argument consistency rules are shown above for
1386 * check_generic_type_consistency().
1388 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1389 * argument, we attempt to deduce the actual type it should have. If
1390 * successful, we alter that position of declared_arg_types[] so that
1391 * make_fn_arguments will coerce the literal to the right thing.
1393 * Rules are applied to the function's return type (possibly altering it)
1394 * if it is declared as a polymorphic type:
1396 * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1397 * argument's actual type as the function's return type.
1398 * 2) If return type is ANYARRAY, no argument is ANYARRAY, but any argument
1399 * is ANYELEMENT, use the actual type of the argument to determine
1400 * the function's return type, i.e. the element type's corresponding
1402 * 3) If return type is ANYARRAY, no argument is ANYARRAY or ANYELEMENT,
1403 * generate an ERROR. This condition is prevented by CREATE FUNCTION
1404 * and is therefore not expected here.
1405 * 4) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1406 * argument's actual type as the function's return type.
1407 * 5) If return type is ANYELEMENT, no argument is ANYELEMENT, but any
1408 * argument is ANYARRAY, use the actual type of the argument to determine
1409 * the function's return type, i.e. the array type's corresponding
1411 * 6) If return type is ANYELEMENT, no argument is ANYARRAY or ANYELEMENT,
1412 * generate an ERROR. This condition is prevented by CREATE FUNCTION
1413 * and is therefore not expected here.
1414 * 7) ANYENUM is treated the same as ANYELEMENT except that if it is used
1415 * (alone or in combination with plain ANYELEMENT), we add the extra
1416 * condition that the ANYELEMENT type must be an enum.
1417 * 8) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1418 * we add the extra condition that the ANYELEMENT type must not be an array.
1419 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1420 * is an extra restriction if not.)
1422 * When allow_poly is false, we are not expecting any of the actual_arg_types
1423 * to be polymorphic, and we should not return a polymorphic result type
1424 * either. When allow_poly is true, it is okay to have polymorphic "actual"
1425 * arg types, and we can return ANYARRAY or ANYELEMENT as the result. (This
1426 * case is currently used only to check compatibility of an aggregate's
1427 * declaration with the underlying transfn.)
1429 * A special case is that we could see ANYARRAY as an actual_arg_type even
1430 * when allow_poly is false (this is possible only because pg_statistic has
1431 * columns shown as anyarray in the catalogs). We allow this to match a
1432 * declared ANYARRAY argument, but only if there is no ANYELEMENT argument
1433 * or result (since we can't determine a specific element type to match to
1434 * ANYELEMENT). Note this means that functions taking ANYARRAY had better
1435 * behave sanely if applied to the pg_statistic columns; they can't just
1436 * assume that successive inputs are of the same actual element type.
1439 enforce_generic_type_consistency(Oid *actual_arg_types,
1440 Oid *declared_arg_types,
1446 bool have_generics = false;
1447 bool have_unknowns = false;
1448 Oid elem_typeid = InvalidOid;
1449 Oid array_typeid = InvalidOid;
1451 bool have_anyelement = (rettype == ANYELEMENTOID ||
1452 rettype == ANYNONARRAYOID ||
1453 rettype == ANYENUMOID);
1454 bool have_anynonarray = (rettype == ANYNONARRAYOID);
1455 bool have_anyenum = (rettype == ANYENUMOID);
1458 * Loop through the arguments to see if we have any that are polymorphic.
1459 * If so, require the actual types to be consistent.
1461 for (j = 0; j < nargs; j++)
1463 Oid decl_type = declared_arg_types[j];
1464 Oid actual_type = actual_arg_types[j];
1466 if (decl_type == ANYELEMENTOID ||
1467 decl_type == ANYNONARRAYOID ||
1468 decl_type == ANYENUMOID)
1470 have_generics = have_anyelement = true;
1471 if (decl_type == ANYNONARRAYOID)
1472 have_anynonarray = true;
1473 else if (decl_type == ANYENUMOID)
1474 have_anyenum = true;
1475 if (actual_type == UNKNOWNOID)
1477 have_unknowns = true;
1480 if (allow_poly && decl_type == actual_type)
1481 continue; /* no new information here */
1482 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1484 (errcode(ERRCODE_DATATYPE_MISMATCH),
1485 errmsg("arguments declared \"anyelement\" are not all alike"),
1486 errdetail("%s versus %s",
1487 format_type_be(elem_typeid),
1488 format_type_be(actual_type))));
1489 elem_typeid = actual_type;
1491 else if (decl_type == ANYARRAYOID)
1493 have_generics = true;
1494 if (actual_type == UNKNOWNOID)
1496 have_unknowns = true;
1499 if (allow_poly && decl_type == actual_type)
1500 continue; /* no new information here */
1501 if (OidIsValid(array_typeid) && actual_type != array_typeid)
1503 (errcode(ERRCODE_DATATYPE_MISMATCH),
1504 errmsg("arguments declared \"anyarray\" are not all alike"),
1505 errdetail("%s versus %s",
1506 format_type_be(array_typeid),
1507 format_type_be(actual_type))));
1508 array_typeid = actual_type;
1513 * Fast Track: if none of the arguments are polymorphic, return the
1514 * unmodified rettype. We assume it can't be polymorphic either.
1519 /* Get the element type based on the array type, if we have one */
1520 if (OidIsValid(array_typeid))
1522 if (array_typeid == ANYARRAYOID && !have_anyelement)
1524 /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1525 array_typelem = InvalidOid;
1529 array_typelem = get_element_type(array_typeid);
1530 if (!OidIsValid(array_typelem))
1532 (errcode(ERRCODE_DATATYPE_MISMATCH),
1533 errmsg("argument declared \"anyarray\" is not an array but type %s",
1534 format_type_be(array_typeid))));
1537 if (!OidIsValid(elem_typeid))
1540 * if we don't have an element type yet, use the one we just got
1542 elem_typeid = array_typelem;
1544 else if (array_typelem != elem_typeid)
1546 /* otherwise, they better match */
1548 (errcode(ERRCODE_DATATYPE_MISMATCH),
1549 errmsg("argument declared \"anyarray\" is not consistent with argument declared \"anyelement\""),
1550 errdetail("%s versus %s",
1551 format_type_be(array_typeid),
1552 format_type_be(elem_typeid))));
1555 else if (!OidIsValid(elem_typeid))
1559 array_typeid = ANYARRAYOID;
1560 elem_typeid = ANYELEMENTOID;
1564 /* Only way to get here is if all the generic args are UNKNOWN */
1566 (errcode(ERRCODE_DATATYPE_MISMATCH),
1567 errmsg("could not determine polymorphic type because input has type \"unknown\"")));
1571 if (have_anynonarray && elem_typeid != ANYELEMENTOID)
1573 /* require the element type to not be an array */
1574 if (type_is_array(elem_typeid))
1576 (errcode(ERRCODE_DATATYPE_MISMATCH),
1577 errmsg("type matched to anynonarray is an array type: %s",
1578 format_type_be(elem_typeid))));
1581 if (have_anyenum && elem_typeid != ANYELEMENTOID)
1583 /* require the element type to be an enum */
1584 if (!type_is_enum(elem_typeid))
1586 (errcode(ERRCODE_DATATYPE_MISMATCH),
1587 errmsg("type matched to anyenum is not an enum type: %s",
1588 format_type_be(elem_typeid))));
1592 * If we had any unknown inputs, re-scan to assign correct types
1596 for (j = 0; j < nargs; j++)
1598 Oid decl_type = declared_arg_types[j];
1599 Oid actual_type = actual_arg_types[j];
1601 if (actual_type != UNKNOWNOID)
1604 if (decl_type == ANYELEMENTOID ||
1605 decl_type == ANYNONARRAYOID ||
1606 decl_type == ANYENUMOID)
1607 declared_arg_types[j] = elem_typeid;
1608 else if (decl_type == ANYARRAYOID)
1610 if (!OidIsValid(array_typeid))
1612 array_typeid = get_array_type(elem_typeid);
1613 if (!OidIsValid(array_typeid))
1615 (errcode(ERRCODE_UNDEFINED_OBJECT),
1616 errmsg("could not find array type for data type %s",
1617 format_type_be(elem_typeid))));
1619 declared_arg_types[j] = array_typeid;
1624 /* if we return ANYARRAY use the appropriate argument type */
1625 if (rettype == ANYARRAYOID)
1627 if (!OidIsValid(array_typeid))
1629 array_typeid = get_array_type(elem_typeid);
1630 if (!OidIsValid(array_typeid))
1632 (errcode(ERRCODE_UNDEFINED_OBJECT),
1633 errmsg("could not find array type for data type %s",
1634 format_type_be(elem_typeid))));
1636 return array_typeid;
1639 /* if we return ANYELEMENT use the appropriate argument type */
1640 if (rettype == ANYELEMENTOID ||
1641 rettype == ANYNONARRAYOID ||
1642 rettype == ANYENUMOID)
1645 /* we don't return a generic type; send back the original return type */
1650 * resolve_generic_type()
1651 * Deduce an individual actual datatype on the assumption that
1652 * the rules for polymorphic types are being followed.
1654 * declared_type is the declared datatype we want to resolve.
1655 * context_actual_type is the actual input datatype to some argument
1656 * that has declared datatype context_declared_type.
1658 * If declared_type isn't polymorphic, we just return it. Otherwise,
1659 * context_declared_type must be polymorphic, and we deduce the correct
1660 * return type based on the relationship of the two polymorphic types.
1663 resolve_generic_type(Oid declared_type,
1664 Oid context_actual_type,
1665 Oid context_declared_type)
1667 if (declared_type == ANYARRAYOID)
1669 if (context_declared_type == ANYARRAYOID)
1671 /* Use actual type, but it must be an array */
1672 Oid array_typelem = get_element_type(context_actual_type);
1674 if (!OidIsValid(array_typelem))
1676 (errcode(ERRCODE_DATATYPE_MISMATCH),
1677 errmsg("argument declared \"anyarray\" is not an array but type %s",
1678 format_type_be(context_actual_type))));
1679 return context_actual_type;
1681 else if (context_declared_type == ANYELEMENTOID ||
1682 context_declared_type == ANYNONARRAYOID ||
1683 context_declared_type == ANYENUMOID)
1685 /* Use the array type corresponding to actual type */
1686 Oid array_typeid = get_array_type(context_actual_type);
1688 if (!OidIsValid(array_typeid))
1690 (errcode(ERRCODE_UNDEFINED_OBJECT),
1691 errmsg("could not find array type for data type %s",
1692 format_type_be(context_actual_type))));
1693 return array_typeid;
1696 else if (declared_type == ANYELEMENTOID ||
1697 declared_type == ANYNONARRAYOID ||
1698 declared_type == ANYENUMOID)
1700 if (context_declared_type == ANYARRAYOID)
1702 /* Use the element type corresponding to actual type */
1703 Oid array_typelem = get_element_type(context_actual_type);
1705 if (!OidIsValid(array_typelem))
1707 (errcode(ERRCODE_DATATYPE_MISMATCH),
1708 errmsg("argument declared \"anyarray\" is not an array but type %s",
1709 format_type_be(context_actual_type))));
1710 return array_typelem;
1712 else if (context_declared_type == ANYELEMENTOID ||
1713 context_declared_type == ANYNONARRAYOID ||
1714 context_declared_type == ANYENUMOID)
1716 /* Use the actual type; it doesn't matter if array or not */
1717 return context_actual_type;
1722 /* declared_type isn't polymorphic, so return it as-is */
1723 return declared_type;
1725 /* If we get here, declared_type is polymorphic and context isn't */
1726 /* NB: this is a calling-code logic error, not a user error */
1727 elog(ERROR, "could not determine polymorphic type because context isn't polymorphic");
1728 return InvalidOid; /* keep compiler quiet */
1733 * Assign a category to the specified type OID.
1735 * NB: this must not return TYPCATEGORY_INVALID.
1738 TypeCategory(Oid type)
1741 bool typispreferred;
1743 get_type_category_preferred(type, &typcategory, &typispreferred);
1744 Assert(typcategory != TYPCATEGORY_INVALID);
1745 return (TYPCATEGORY) typcategory;
1749 /* IsPreferredType()
1750 * Check if this type is a preferred type for the given category.
1752 * If category is TYPCATEGORY_INVALID, then we'll return TRUE for preferred
1753 * types of any category; otherwise, only for preferred types of that
1757 IsPreferredType(TYPCATEGORY category, Oid type)
1760 bool typispreferred;
1762 get_type_category_preferred(type, &typcategory, &typispreferred);
1763 if (category == typcategory || category == TYPCATEGORY_INVALID)
1764 return typispreferred;
1770 /* IsBinaryCoercible()
1771 * Check if srctype is binary-coercible to targettype.
1773 * This notion allows us to cheat and directly exchange values without
1774 * going through the trouble of calling a conversion function. Note that
1775 * in general, this should only be an implementation shortcut. Before 7.4,
1776 * this was also used as a heuristic for resolving overloaded functions and
1777 * operators, but that's basically a bad idea.
1779 * As of 7.3, binary coercibility isn't hardwired into the code anymore.
1780 * We consider two types binary-coercible if there is an implicitly
1781 * invokable, no-function-needed pg_cast entry. Also, a domain is always
1782 * binary-coercible to its base type, though *not* vice versa (in the other
1783 * direction, one must apply domain constraint checks before accepting the
1784 * value as legitimate). We also need to special-case various polymorphic
1787 * This function replaces IsBinaryCompatible(), which was an inherently
1788 * symmetric test. Since the pg_cast entries aren't necessarily symmetric,
1789 * the order of the operands is now significant.
1792 IsBinaryCoercible(Oid srctype, Oid targettype)
1795 Form_pg_cast castForm;
1798 /* Fast path if same type */
1799 if (srctype == targettype)
1802 /* If srctype is a domain, reduce to its base type */
1803 if (OidIsValid(srctype))
1804 srctype = getBaseType(srctype);
1806 /* Somewhat-fast path for domain -> base type case */
1807 if (srctype == targettype)
1810 /* Also accept any array type as coercible to ANYARRAY */
1811 if (targettype == ANYARRAYOID)
1812 if (type_is_array(srctype))
1815 /* Also accept any non-array type as coercible to ANYNONARRAY */
1816 if (targettype == ANYNONARRAYOID)
1817 if (!type_is_array(srctype))
1820 /* Also accept any enum type as coercible to ANYENUM */
1821 if (targettype == ANYENUMOID)
1822 if (type_is_enum(srctype))
1825 /* Also accept any composite type as coercible to RECORD */
1826 if (targettype == RECORDOID)
1827 if (ISCOMPLEX(srctype))
1830 /* Also accept any composite array type as coercible to RECORD[] */
1831 if (targettype == RECORDARRAYOID)
1832 if (is_complex_array(srctype))
1835 /* Else look in pg_cast */
1836 tuple = SearchSysCache(CASTSOURCETARGET,
1837 ObjectIdGetDatum(srctype),
1838 ObjectIdGetDatum(targettype),
1840 if (!HeapTupleIsValid(tuple))
1841 return false; /* no cast */
1842 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1844 result = (castForm->castfunc == InvalidOid &&
1845 castForm->castcontext == COERCION_CODE_IMPLICIT);
1847 ReleaseSysCache(tuple);
1854 * find_coercion_pathway
1855 * Look for a coercion pathway between two types.
1857 * Currently, this deals only with scalar-type cases; it does not consider
1858 * polymorphic types nor casts between composite types. (Perhaps fold
1859 * those in someday?)
1861 * ccontext determines the set of available casts.
1863 * The possible result codes are:
1864 * COERCION_PATH_NONE: failed to find any coercion pathway
1865 * *funcid is set to InvalidOid
1866 * COERCION_PATH_FUNC: apply the coercion function returned in *funcid
1867 * COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
1868 * *funcid is set to InvalidOid
1869 * COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
1870 * *funcid is set to the element cast function, or InvalidOid
1871 * if the array elements are binary-compatible
1872 * COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
1873 * *funcid is set to InvalidOid
1875 * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
1876 * needed to do the coercion; if the target is a domain then we may need to
1877 * apply domain constraint checking. If you want to check for a zero-effort
1878 * conversion then use IsBinaryCoercible().
1881 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
1882 CoercionContext ccontext,
1885 CoercionPathType result = COERCION_PATH_NONE;
1888 *funcid = InvalidOid;
1890 /* Perhaps the types are domains; if so, look at their base types */
1891 if (OidIsValid(sourceTypeId))
1892 sourceTypeId = getBaseType(sourceTypeId);
1893 if (OidIsValid(targetTypeId))
1894 targetTypeId = getBaseType(targetTypeId);
1896 /* Domains are always coercible to and from their base type */
1897 if (sourceTypeId == targetTypeId)
1898 return COERCION_PATH_RELABELTYPE;
1900 /* Look in pg_cast */
1901 tuple = SearchSysCache(CASTSOURCETARGET,
1902 ObjectIdGetDatum(sourceTypeId),
1903 ObjectIdGetDatum(targetTypeId),
1906 if (HeapTupleIsValid(tuple))
1908 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1909 CoercionContext castcontext;
1911 /* convert char value for castcontext to CoercionContext enum */
1912 switch (castForm->castcontext)
1914 case COERCION_CODE_IMPLICIT:
1915 castcontext = COERCION_IMPLICIT;
1917 case COERCION_CODE_ASSIGNMENT:
1918 castcontext = COERCION_ASSIGNMENT;
1920 case COERCION_CODE_EXPLICIT:
1921 castcontext = COERCION_EXPLICIT;
1924 elog(ERROR, "unrecognized castcontext: %d",
1925 (int) castForm->castcontext);
1926 castcontext = 0; /* keep compiler quiet */
1930 /* Rely on ordering of enum for correct behavior here */
1931 if (ccontext >= castcontext)
1933 switch (castForm->castmethod)
1935 case COERCION_METHOD_FUNCTION:
1936 result = COERCION_PATH_FUNC;
1937 *funcid = castForm->castfunc;
1939 case COERCION_METHOD_INOUT:
1940 result = COERCION_PATH_COERCEVIAIO;
1942 case COERCION_METHOD_BINARY:
1943 result = COERCION_PATH_RELABELTYPE;
1946 elog(ERROR, "unrecognized castmethod: %d",
1947 (int) castForm->castmethod);
1952 ReleaseSysCache(tuple);
1957 * If there's no pg_cast entry, perhaps we are dealing with a pair of
1958 * array types. If so, and if the element types have a suitable cast,
1959 * report that we can coerce with an ArrayCoerceExpr.
1961 * Hack: disallow coercions to oidvector and int2vector, which
1962 * otherwise tend to capture coercions that should go to "real" array
1963 * types. We want those types to be considered "real" arrays for many
1964 * purposes, but not this one. (Also, ArrayCoerceExpr isn't
1965 * guaranteed to produce an output that meets the restrictions of
1966 * these datatypes, such as being 1-dimensional.)
1968 if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
1973 if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
1974 (sourceElem = get_element_type(sourceTypeId)) != InvalidOid)
1976 CoercionPathType elempathtype;
1979 elempathtype = find_coercion_pathway(targetElem,
1983 if (elempathtype != COERCION_PATH_NONE &&
1984 elempathtype != COERCION_PATH_ARRAYCOERCE)
1986 *funcid = elemfuncid;
1987 if (elempathtype == COERCION_PATH_COERCEVIAIO)
1988 result = COERCION_PATH_COERCEVIAIO;
1990 result = COERCION_PATH_ARRAYCOERCE;
1996 * If we still haven't found a possibility, consider automatic casting
1997 * using I/O functions. We allow assignment casts to string types
1998 * and explicit casts from string types to be handled this way. (The
1999 * CoerceViaIO mechanism is a lot more general than that, but this is
2000 * all we want to allow in the absence of a pg_cast entry.) It would
2001 * probably be better to insist on explicit casts in both directions,
2002 * but this is a compromise to preserve something of the pre-8.3
2003 * behavior that many types had implicit (yipes!) casts to text.
2005 if (result == COERCION_PATH_NONE)
2007 if (ccontext >= COERCION_ASSIGNMENT &&
2008 TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
2009 result = COERCION_PATH_COERCEVIAIO;
2010 else if (ccontext >= COERCION_EXPLICIT &&
2011 TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
2012 result = COERCION_PATH_COERCEVIAIO;
2021 * find_typmod_coercion_function -- does the given type need length coercion?
2023 * If the target type possesses a pg_cast function from itself to itself,
2024 * it must need length coercion.
2026 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
2028 * If the given type is a varlena array type, we do not look for a coercion
2029 * function associated directly with the array type, but instead look for
2030 * one associated with the element type. An ArrayCoerceExpr node must be
2031 * used to apply such a function.
2033 * We use the same result enum as find_coercion_pathway, but the only possible
2035 * COERCION_PATH_NONE: no length coercion needed
2036 * COERCION_PATH_FUNC: apply the function returned in *funcid
2037 * COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
2040 find_typmod_coercion_function(Oid typeId,
2043 CoercionPathType result;
2045 Form_pg_type typeForm;
2048 *funcid = InvalidOid;
2049 result = COERCION_PATH_FUNC;
2051 targetType = typeidType(typeId);
2052 typeForm = (Form_pg_type) GETSTRUCT(targetType);
2054 /* Check for a varlena array type (and not a domain) */
2055 if (typeForm->typelem != InvalidOid &&
2056 typeForm->typlen == -1 &&
2057 typeForm->typtype != TYPTYPE_DOMAIN)
2059 /* Yes, switch our attention to the element type */
2060 typeId = typeForm->typelem;
2061 result = COERCION_PATH_ARRAYCOERCE;
2063 ReleaseSysCache(targetType);
2065 /* Look in pg_cast */
2066 tuple = SearchSysCache(CASTSOURCETARGET,
2067 ObjectIdGetDatum(typeId),
2068 ObjectIdGetDatum(typeId),
2071 if (HeapTupleIsValid(tuple))
2073 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2075 *funcid = castForm->castfunc;
2076 ReleaseSysCache(tuple);
2079 if (!OidIsValid(*funcid))
2080 result = COERCION_PATH_NONE;
2087 * Is this type an array of composite?
2089 * Note: this will not return true for record[]; check for RECORDARRAYOID
2090 * separately if needed.
2093 is_complex_array(Oid typid)
2095 Oid elemtype = get_element_type(typid);
2097 return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));