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.176 2009/05/12 03:11:02 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_cast.h"
18 #include "catalog/pg_inherits_fn.h"
19 #include "catalog/pg_proc.h"
20 #include "catalog/pg_type.h"
21 #include "nodes/makefuncs.h"
22 #include "nodes/nodeFuncs.h"
23 #include "parser/parse_coerce.h"
24 #include "parser/parse_func.h"
25 #include "parser/parse_relation.h"
26 #include "parser/parse_type.h"
27 #include "utils/builtins.h"
28 #include "utils/fmgroids.h"
29 #include "utils/lsyscache.h"
30 #include "utils/syscache.h"
31 #include "utils/typcache.h"
34 static Node *coerce_type_typmod(Node *node,
35 Oid targetTypeId, int32 targetTypMod,
36 CoercionForm cformat, int location,
37 bool isExplicit, bool hideInputCoercion);
38 static void hide_coercion_node(Node *node);
39 static Node *build_coercion_expression(Node *node,
40 CoercionPathType pathtype,
42 Oid targetTypeId, int32 targetTypMod,
43 CoercionForm cformat, int location,
45 static Node *coerce_record_to_complex(ParseState *pstate, Node *node,
47 CoercionContext ccontext,
50 static bool is_complex_array(Oid typid);
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,
83 if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
86 result = coerce_type(pstate, expr, exprtype,
87 targettype, targettypmod,
88 ccontext, cformat, location);
91 * If the target is a fixed-length type, it may need a length coercion as
92 * well as a type coercion. If we find ourselves adding both, force the
93 * inner coercion node to implicit display form.
95 result = coerce_type_typmod(result,
96 targettype, targettypmod,
98 (cformat != COERCE_IMPLICIT_CAST),
99 (result != expr && !IsA(result, Const)));
107 * Convert an expression to a different type.
109 * The caller should already have determined that the coercion is possible;
110 * see can_coerce_type.
112 * Normally, no coercion to a typmod (length) is performed here. The caller
113 * must call coerce_type_typmod as well, if a typmod constraint is wanted.
114 * (But if the target type is a domain, it may internally contain a
115 * typmod constraint, which will be applied inside coerce_to_domain.)
116 * In some cases pg_cast specifies a type coercion function that also
117 * applies length conversion, and in those cases only, the result will
118 * already be properly coerced to the specified typmod.
120 * pstate is only used in the case that we are able to resolve the type of
121 * a previously UNKNOWN Param. It is okay to pass pstate = NULL if the
122 * caller does not want type information updated for Params.
125 coerce_type(ParseState *pstate, Node *node,
126 Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
127 CoercionContext ccontext, CoercionForm cformat, int location)
130 CoercionPathType pathtype;
133 if (targetTypeId == inputTypeId ||
136 /* no conversion needed */
139 if (targetTypeId == ANYOID ||
140 targetTypeId == ANYELEMENTOID ||
141 targetTypeId == ANYNONARRAYOID ||
142 (targetTypeId == ANYARRAYOID && inputTypeId != UNKNOWNOID) ||
143 (targetTypeId == ANYENUMOID && inputTypeId != UNKNOWNOID))
146 * Assume can_coerce_type verified that implicit coercion is okay.
148 * Note: by returning the unmodified node here, we are saying that
149 * it's OK to treat an UNKNOWN constant as a valid input for a
150 * function accepting ANY, ANYELEMENT, or ANYNONARRAY. This should be
151 * all right, since an UNKNOWN value is still a perfectly valid Datum.
152 * However an UNKNOWN value is definitely *not* an array, and so we
153 * mustn't accept it for ANYARRAY. (Instead, we will call anyarray_in
154 * below, which will produce an error.) Likewise, UNKNOWN input is no
157 * NB: we do NOT want a RelabelType here.
161 if (inputTypeId == UNKNOWNOID && IsA(node, Const))
164 * Input is a string constant with previously undetermined type. Apply
165 * the target type's typinput function to it to produce a constant of
168 * NOTE: this case cannot be folded together with the other
169 * constant-input case, since the typinput function does not
170 * necessarily behave the same as a type conversion function. For
171 * example, int4's typinput function will reject "1.2", whereas
172 * float-to-int type conversion will round to integer.
174 * XXX if the typinput function is not immutable, we really ought to
175 * postpone evaluation of the function call until runtime. But there
176 * is no way to represent a typinput function call as an expression
177 * tree, because C-string values are not Datums. (XXX This *is*
178 * possible as of 7.3, do we want to do it?)
180 Const *con = (Const *) node;
181 Const *newcon = makeNode(Const);
186 ParseCallbackState pcbstate;
189 * If the target type is a domain, we want to call its base type's
190 * input routine, not domain_in(). This is to avoid premature failure
191 * when the domain applies a typmod: existing input routines follow
192 * implicit-coercion semantics for length checks, which is not always
193 * what we want here. The needed check will be applied properly
194 * inside coerce_to_domain().
196 baseTypeMod = targetTypeMod;
197 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
200 * For most types we pass typmod -1 to the input routine, because
201 * existing input routines follow implicit-coercion semantics for
202 * length checks, which is not always what we want here. Any length
203 * constraint will be applied later by our caller. An exception
204 * however is the INTERVAL type, for which we *must* pass the typmod
205 * or it won't be able to obey the bizarre SQL-spec input rules.
206 * (Ugly as sin, but so is this part of the spec...)
208 if (baseTypeId == INTERVALOID)
209 inputTypeMod = baseTypeMod;
213 targetType = typeidType(baseTypeId);
215 newcon->consttype = baseTypeId;
216 newcon->consttypmod = inputTypeMod;
217 newcon->constlen = typeLen(targetType);
218 newcon->constbyval = typeByVal(targetType);
219 newcon->constisnull = con->constisnull;
220 /* Use the leftmost of the constant's and coercion's locations */
222 newcon->location = con->location;
223 else if (con->location >= 0 && con->location < location)
224 newcon->location = con->location;
226 newcon->location = location;
229 * Set up to point at the constant's text if the input routine
232 setup_parser_errposition_callback(&pcbstate, pstate, con->location);
235 * We assume here that UNKNOWN's internal representation is the same
238 if (!con->constisnull)
239 newcon->constvalue = stringTypeDatum(targetType,
240 DatumGetCString(con->constvalue),
243 newcon->constvalue = stringTypeDatum(targetType,
247 cancel_parser_errposition_callback(&pcbstate);
249 result = (Node *) newcon;
251 /* If target is a domain, apply constraints. */
252 if (baseTypeId != targetTypeId)
253 result = coerce_to_domain(result,
254 baseTypeId, baseTypeMod,
256 cformat, location, false, false);
258 ReleaseSysCache(targetType);
262 if (inputTypeId == UNKNOWNOID && IsA(node, Param) &&
263 ((Param *) node)->paramkind == PARAM_EXTERN &&
264 pstate != NULL && pstate->p_variableparams)
267 * Input is a Param of previously undetermined type, and we want to
268 * update our knowledge of the Param's type. Find the topmost
269 * ParseState and update the state.
271 Param *param = (Param *) node;
272 int paramno = param->paramid;
273 ParseState *toppstate;
276 while (toppstate->parentParseState != NULL)
277 toppstate = toppstate->parentParseState;
279 if (paramno <= 0 || /* shouldn't happen, but... */
280 paramno > toppstate->p_numparams)
282 (errcode(ERRCODE_UNDEFINED_PARAMETER),
283 errmsg("there is no parameter $%d", paramno),
284 parser_errposition(pstate, param->location)));
286 if (toppstate->p_paramtypes[paramno - 1] == UNKNOWNOID)
288 /* We've successfully resolved the type */
289 toppstate->p_paramtypes[paramno - 1] = targetTypeId;
291 else if (toppstate->p_paramtypes[paramno - 1] == targetTypeId)
293 /* We previously resolved the type, and it matches */
299 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
300 errmsg("inconsistent types deduced for parameter $%d",
302 errdetail("%s versus %s",
303 format_type_be(toppstate->p_paramtypes[paramno - 1]),
304 format_type_be(targetTypeId)),
305 parser_errposition(pstate, param->location)));
308 param->paramtype = targetTypeId;
311 * Note: it is tempting here to set the Param's paramtypmod to
312 * targetTypeMod, but that is probably unwise because we have no
313 * infrastructure that enforces that the value delivered for a Param
314 * will match any particular typmod. Leaving it -1 ensures that a
315 * run-time length check/coercion will occur if needed.
317 param->paramtypmod = -1;
319 /* Use the leftmost of the param's and coercion's locations */
321 (param->location < 0 || location < param->location))
322 param->location = location;
324 return (Node *) param;
326 pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
328 if (pathtype != COERCION_PATH_NONE)
330 if (pathtype != COERCION_PATH_RELABELTYPE)
333 * Generate an expression tree representing run-time application
334 * of the conversion function. If we are dealing with a domain
335 * target type, the conversion function will yield the base type,
336 * and we need to extract the correct typmod to use from the
337 * domain's typtypmod.
342 baseTypeMod = targetTypeMod;
343 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
345 result = build_coercion_expression(node, pathtype, funcId,
346 baseTypeId, baseTypeMod,
348 (cformat != COERCE_IMPLICIT_CAST));
351 * If domain, coerce to the domain type and relabel with domain
352 * type ID. We can skip the internal length-coercion step if the
353 * selected coercion function was a type-and-length coercion.
355 if (targetTypeId != baseTypeId)
356 result = coerce_to_domain(result, baseTypeId, baseTypeMod,
358 cformat, location, true,
359 exprIsLengthCoercion(result,
365 * We don't need to do a physical conversion, but we do need to
366 * attach a RelabelType node so that the expression will be seen
367 * to have the intended type when inspected by higher-level code.
369 * Also, domains may have value restrictions beyond the base type
370 * that must be accounted for. If the destination is a domain
371 * then we won't need a RelabelType node.
373 result = coerce_to_domain(node, InvalidOid, -1, targetTypeId,
374 cformat, location, false, false);
378 * XXX could we label result with exprTypmod(node) instead of
379 * default -1 typmod, to save a possible length-coercion
380 * later? Would work if both types have same interpretation of
381 * typmod, which is likely but not certain.
383 RelabelType *r = makeRelabelType((Expr *) result,
387 r->location = location;
393 if (inputTypeId == RECORDOID &&
394 ISCOMPLEX(targetTypeId))
396 /* Coerce a RECORD to a specific complex type */
397 return coerce_record_to_complex(pstate, node, targetTypeId,
398 ccontext, cformat, location);
400 if (targetTypeId == RECORDOID &&
401 ISCOMPLEX(inputTypeId))
403 /* Coerce a specific complex type to RECORD */
404 /* NB: we do NOT want a RelabelType here */
408 if (inputTypeId == RECORDARRAYOID &&
409 is_complex_array(targetTypeId))
411 /* Coerce record[] to a specific complex array type */
412 /* not implemented yet ... */
415 if (targetTypeId == RECORDARRAYOID &&
416 is_complex_array(inputTypeId))
418 /* Coerce a specific complex array type to record[] */
419 /* NB: we do NOT want a RelabelType here */
422 if (typeInheritsFrom(inputTypeId, targetTypeId))
425 * Input class type is a subclass of target, so generate an
426 * appropriate runtime conversion (removing unneeded columns and
427 * possibly rearranging the ones that are wanted).
429 ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
431 r->arg = (Expr *) node;
432 r->resulttype = targetTypeId;
433 r->convertformat = cformat;
434 r->location = location;
437 /* If we get here, caller blew it */
438 elog(ERROR, "failed to find conversion function from %s to %s",
439 format_type_be(inputTypeId), format_type_be(targetTypeId));
440 return NULL; /* keep compiler quiet */
446 * Can input_typeids be coerced to target_typeids?
448 * We must be told the context (CAST construct, assignment, implicit coercion)
449 * as this determines the set of available casts.
452 can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids,
453 CoercionContext ccontext)
455 bool have_generics = false;
458 /* run through argument list... */
459 for (i = 0; i < nargs; i++)
461 Oid inputTypeId = input_typeids[i];
462 Oid targetTypeId = target_typeids[i];
463 CoercionPathType pathtype;
466 /* no problem if same type */
467 if (inputTypeId == targetTypeId)
470 /* accept if target is ANY */
471 if (targetTypeId == ANYOID)
474 /* accept if target is polymorphic, for now */
475 if (IsPolymorphicType(targetTypeId))
477 have_generics = true; /* do more checking later */
482 * If input is an untyped string constant, assume we can convert it to
485 if (inputTypeId == UNKNOWNOID)
489 * If pg_cast shows that we can coerce, accept. This test now covers
490 * both binary-compatible and coercion-function cases.
492 pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
494 if (pathtype != COERCION_PATH_NONE)
498 * If input is RECORD and target is a composite type, assume we can
499 * coerce (may need tighter checking here)
501 if (inputTypeId == RECORDOID &&
502 ISCOMPLEX(targetTypeId))
506 * If input is a composite type and target is RECORD, accept
508 if (targetTypeId == RECORDOID &&
509 ISCOMPLEX(inputTypeId))
512 #ifdef NOT_USED /* not implemented yet */
514 * If input is record[] and target is a composite array type,
515 * assume we can coerce (may need tighter checking here)
517 if (inputTypeId == RECORDARRAYOID &&
518 is_complex_array(targetTypeId))
523 * If input is a composite array type and target is record[], accept
525 if (targetTypeId == RECORDARRAYOID &&
526 is_complex_array(inputTypeId))
530 * If input is a class type that inherits from target, accept
532 if (typeInheritsFrom(inputTypeId, targetTypeId))
536 * Else, cannot coerce at this argument position
541 /* If we found any generic argument types, cross-check them */
544 if (!check_generic_type_consistency(input_typeids, target_typeids,
554 * Create an expression tree to represent coercion to a domain type.
556 * 'arg': input expression
557 * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
558 * has not bothered to look this up)
559 * 'baseTypeMod': base type typmod of domain, if known (pass -1 if caller
560 * has not bothered to look this up)
561 * 'typeId': target type to coerce to
562 * 'cformat': coercion format
563 * 'location': coercion request location
564 * 'hideInputCoercion': if true, hide the input coercion under this one.
565 * 'lengthCoercionDone': if true, caller already accounted for length,
566 * ie the input is already of baseTypMod as well as baseTypeId.
568 * If the target type isn't a domain, the given 'arg' is returned as-is.
571 coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId,
572 CoercionForm cformat, int location,
573 bool hideInputCoercion,
574 bool lengthCoercionDone)
576 CoerceToDomain *result;
578 /* Get the base type if it hasn't been supplied */
579 if (baseTypeId == InvalidOid)
580 baseTypeId = getBaseTypeAndTypmod(typeId, &baseTypeMod);
582 /* If it isn't a domain, return the node as it was passed in */
583 if (baseTypeId == typeId)
586 /* Suppress display of nested coercion steps */
587 if (hideInputCoercion)
588 hide_coercion_node(arg);
591 * If the domain applies a typmod to its base type, build the appropriate
592 * coercion step. Mark it implicit for display purposes, because we don't
593 * want it shown separately by ruleutils.c; but the isExplicit flag passed
594 * to the conversion function depends on the manner in which the domain
595 * coercion is invoked, so that the semantics of implicit and explicit
596 * coercion differ. (Is that really the behavior we want?)
598 * NOTE: because we apply this as part of the fixed expression structure,
599 * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that that
600 * would be safe to do anyway, without lots of knowledge about what the
601 * base type thinks the typmod means.
603 if (!lengthCoercionDone)
605 if (baseTypeMod >= 0)
606 arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
607 COERCE_IMPLICIT_CAST, location,
608 (cformat != COERCE_IMPLICIT_CAST),
613 * Now build the domain coercion node. This represents run-time checking
614 * of any constraints currently attached to the domain. This also ensures
615 * that the expression is properly labeled as to result type.
617 result = makeNode(CoerceToDomain);
618 result->arg = (Expr *) arg;
619 result->resulttype = typeId;
620 result->resulttypmod = -1; /* currently, always -1 for domains */
621 result->coercionformat = cformat;
622 result->location = location;
624 return (Node *) result;
629 * coerce_type_typmod()
630 * Force a value to a particular typmod, if meaningful and possible.
632 * This is applied to values that are going to be stored in a relation
633 * (where we have an atttypmod for the column) as well as values being
634 * explicitly CASTed (where the typmod comes from the target type spec).
636 * The caller must have already ensured that the value is of the correct
637 * type, typically by applying coerce_type.
639 * cformat determines the display properties of the generated node (if any),
640 * while isExplicit may affect semantics. If hideInputCoercion is true
641 * *and* we generate a node, the input node is forced to IMPLICIT display
642 * form, so that only the typmod coercion node will be visible when
643 * displaying the expression.
645 * NOTE: this does not need to work on domain types, because any typmod
646 * coercion for a domain is considered to be part of the type coercion
647 * needed to produce the domain value in the first place. So, no getBaseType.
650 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
651 CoercionForm cformat, int location,
652 bool isExplicit, bool hideInputCoercion)
654 CoercionPathType pathtype;
658 * A negative typmod is assumed to mean that no coercion is wanted. Also,
659 * skip coercion if already done.
661 if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
664 pathtype = find_typmod_coercion_function(targetTypeId, &funcId);
666 if (pathtype != COERCION_PATH_NONE)
668 /* Suppress display of nested coercion steps */
669 if (hideInputCoercion)
670 hide_coercion_node(node);
672 node = build_coercion_expression(node, pathtype, funcId,
673 targetTypeId, targetTypMod,
682 * Mark a coercion node as IMPLICIT so it will never be displayed by
683 * ruleutils.c. We use this when we generate a nest of coercion nodes
684 * to implement what is logically one conversion; the inner nodes are
685 * forced to IMPLICIT_CAST format. This does not change their semantics,
686 * only display behavior.
688 * It is caller error to call this on something that doesn't have a
689 * CoercionForm field.
692 hide_coercion_node(Node *node)
694 if (IsA(node, FuncExpr))
695 ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
696 else if (IsA(node, RelabelType))
697 ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
698 else if (IsA(node, CoerceViaIO))
699 ((CoerceViaIO *) node)->coerceformat = COERCE_IMPLICIT_CAST;
700 else if (IsA(node, ArrayCoerceExpr))
701 ((ArrayCoerceExpr *) node)->coerceformat = COERCE_IMPLICIT_CAST;
702 else if (IsA(node, ConvertRowtypeExpr))
703 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
704 else if (IsA(node, RowExpr))
705 ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
706 else if (IsA(node, CoerceToDomain))
707 ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
709 elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
713 * build_coercion_expression()
714 * Construct an expression tree for applying a pg_cast entry.
716 * This is used for both type-coercion and length-coercion operations,
717 * since there is no difference in terms of the calling convention.
720 build_coercion_expression(Node *node,
721 CoercionPathType pathtype,
723 Oid targetTypeId, int32 targetTypMod,
724 CoercionForm cformat, int location,
729 if (OidIsValid(funcId))
732 Form_pg_proc procstruct;
734 tp = SearchSysCache(PROCOID,
735 ObjectIdGetDatum(funcId),
737 if (!HeapTupleIsValid(tp))
738 elog(ERROR, "cache lookup failed for function %u", funcId);
739 procstruct = (Form_pg_proc) GETSTRUCT(tp);
742 * These Asserts essentially check that function is a legal coercion
743 * function. We can't make the seemingly obvious tests on prorettype
744 * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
745 * various binary-compatibility cases.
747 /* Assert(targetTypeId == procstruct->prorettype); */
748 Assert(!procstruct->proretset);
749 Assert(!procstruct->proisagg);
750 Assert(!procstruct->proiswindow);
751 nargs = procstruct->pronargs;
752 Assert(nargs >= 1 && nargs <= 3);
753 /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
754 Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
755 Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
760 if (pathtype == COERCION_PATH_FUNC)
762 /* We build an ordinary FuncExpr with special arguments */
767 Assert(OidIsValid(funcId));
769 args = list_make1(node);
773 /* Pass target typmod as an int4 constant */
774 cons = makeConst(INT4OID,
777 Int32GetDatum(targetTypMod),
781 args = lappend(args, cons);
786 /* Pass it a boolean isExplicit parameter, too */
787 cons = makeConst(BOOLOID,
790 BoolGetDatum(isExplicit),
794 args = lappend(args, cons);
797 fexpr = makeFuncExpr(funcId, targetTypeId, args, cformat);
798 fexpr->location = location;
799 return (Node *) fexpr;
801 else if (pathtype == COERCION_PATH_ARRAYCOERCE)
803 /* We need to build an ArrayCoerceExpr */
804 ArrayCoerceExpr *acoerce = makeNode(ArrayCoerceExpr);
806 acoerce->arg = (Expr *) node;
807 acoerce->elemfuncid = funcId;
808 acoerce->resulttype = targetTypeId;
811 * Label the output as having a particular typmod only if we are
812 * really invoking a length-coercion function, ie one with more than
815 acoerce->resulttypmod = (nargs >= 2) ? targetTypMod : -1;
816 acoerce->isExplicit = isExplicit;
817 acoerce->coerceformat = cformat;
818 acoerce->location = location;
820 return (Node *) acoerce;
822 else if (pathtype == COERCION_PATH_COERCEVIAIO)
824 /* We need to build a CoerceViaIO node */
825 CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
827 Assert(!OidIsValid(funcId));
829 iocoerce->arg = (Expr *) node;
830 iocoerce->resulttype = targetTypeId;
831 iocoerce->coerceformat = cformat;
832 iocoerce->location = location;
834 return (Node *) iocoerce;
838 elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
840 return NULL; /* keep compiler quiet */
846 * coerce_record_to_complex
847 * Coerce a RECORD to a specific composite type.
849 * Currently we only support this for inputs that are RowExprs or whole-row
853 coerce_record_to_complex(ParseState *pstate, Node *node,
855 CoercionContext ccontext,
856 CoercionForm cformat,
867 if (node && IsA(node, RowExpr))
870 * Since the RowExpr must be of type RECORD, we needn't worry about it
871 * containing any dropped columns.
873 args = ((RowExpr *) node)->args;
875 else if (node && IsA(node, Var) &&
876 ((Var *) node)->varattno == InvalidAttrNumber)
878 int rtindex = ((Var *) node)->varno;
879 int sublevels_up = ((Var *) node)->varlevelsup;
880 int vlocation = ((Var *) node)->location;
883 rte = GetRTEByRangeTablePosn(pstate, rtindex, sublevels_up);
884 expandRTE(rte, rtindex, sublevels_up, vlocation, false,
889 (errcode(ERRCODE_CANNOT_COERCE),
890 errmsg("cannot cast type %s to %s",
891 format_type_be(RECORDOID),
892 format_type_be(targetTypeId)),
893 parser_coercion_errposition(pstate, location, node)));
895 tupdesc = lookup_rowtype_tupdesc(targetTypeId, -1);
898 arg = list_head(args);
899 for (i = 0; i < tupdesc->natts; i++)
905 /* Fill in NULLs for dropped columns in rowtype */
906 if (tupdesc->attrs[i]->attisdropped)
909 * can't use atttypid here, but it doesn't really matter what type
910 * the Const claims to be.
912 newargs = lappend(newargs, makeNullConst(INT4OID, -1));
918 (errcode(ERRCODE_CANNOT_COERCE),
919 errmsg("cannot cast type %s to %s",
920 format_type_be(RECORDOID),
921 format_type_be(targetTypeId)),
922 errdetail("Input has too few columns."),
923 parser_coercion_errposition(pstate, location, node)));
924 expr = (Node *) lfirst(arg);
925 exprtype = exprType(expr);
927 cexpr = coerce_to_target_type(pstate,
929 tupdesc->attrs[i]->atttypid,
930 tupdesc->attrs[i]->atttypmod,
932 COERCE_IMPLICIT_CAST,
936 (errcode(ERRCODE_CANNOT_COERCE),
937 errmsg("cannot cast type %s to %s",
938 format_type_be(RECORDOID),
939 format_type_be(targetTypeId)),
940 errdetail("Cannot cast type %s to %s in column %d.",
941 format_type_be(exprtype),
942 format_type_be(tupdesc->attrs[i]->atttypid),
944 parser_coercion_errposition(pstate, location, expr)));
945 newargs = lappend(newargs, cexpr);
951 (errcode(ERRCODE_CANNOT_COERCE),
952 errmsg("cannot cast type %s to %s",
953 format_type_be(RECORDOID),
954 format_type_be(targetTypeId)),
955 errdetail("Input has too many columns."),
956 parser_coercion_errposition(pstate, location, node)));
958 ReleaseTupleDesc(tupdesc);
960 rowexpr = makeNode(RowExpr);
961 rowexpr->args = newargs;
962 rowexpr->row_typeid = targetTypeId;
963 rowexpr->row_format = cformat;
964 rowexpr->colnames = NIL; /* not needed for named target type */
965 rowexpr->location = location;
966 return (Node *) rowexpr;
970 * coerce_to_boolean()
971 * Coerce an argument of a construct that requires boolean input
972 * (AND, OR, NOT, etc). Also check that input is not a set.
974 * Returns the possibly-transformed node tree.
976 * As with coerce_type, pstate may be NULL if no special unknown-Param
977 * processing is wanted.
980 coerce_to_boolean(ParseState *pstate, Node *node,
981 const char *constructName)
983 Oid inputTypeId = exprType(node);
985 if (inputTypeId != BOOLOID)
989 newnode = coerce_to_target_type(pstate, node, inputTypeId,
992 COERCE_IMPLICIT_CAST,
996 (errcode(ERRCODE_DATATYPE_MISMATCH),
997 /* translator: first %s is name of a SQL construct, eg WHERE */
998 errmsg("argument of %s must be type boolean, not type %s",
999 constructName, format_type_be(inputTypeId)),
1000 parser_errposition(pstate, exprLocation(node))));
1004 if (expression_returns_set(node))
1006 (errcode(ERRCODE_DATATYPE_MISMATCH),
1007 /* translator: %s is name of a SQL construct, eg WHERE */
1008 errmsg("argument of %s must not return a set",
1010 parser_errposition(pstate, exprLocation(node))));
1016 * coerce_to_specific_type()
1017 * Coerce an argument of a construct that requires a specific data type.
1018 * Also check that input is not a set.
1020 * Returns the possibly-transformed node tree.
1022 * As with coerce_type, pstate may be NULL if no special unknown-Param
1023 * processing is wanted.
1026 coerce_to_specific_type(ParseState *pstate, Node *node,
1028 const char *constructName)
1030 Oid inputTypeId = exprType(node);
1032 if (inputTypeId != targetTypeId)
1036 newnode = coerce_to_target_type(pstate, node, inputTypeId,
1038 COERCION_ASSIGNMENT,
1039 COERCE_IMPLICIT_CAST,
1041 if (newnode == NULL)
1043 (errcode(ERRCODE_DATATYPE_MISMATCH),
1044 /* translator: first %s is name of a SQL construct, eg LIMIT */
1045 errmsg("argument of %s must be type %s, not type %s",
1047 format_type_be(targetTypeId),
1048 format_type_be(inputTypeId)),
1049 parser_errposition(pstate, exprLocation(node))));
1053 if (expression_returns_set(node))
1055 (errcode(ERRCODE_DATATYPE_MISMATCH),
1056 /* translator: %s is name of a SQL construct, eg LIMIT */
1057 errmsg("argument of %s must not return a set",
1059 parser_errposition(pstate, exprLocation(node))));
1066 * parser_coercion_errposition - report coercion error location, if possible
1068 * We prefer to point at the coercion request (CAST, ::, etc) if possible;
1069 * but there may be no such location in the case of an implicit coercion.
1070 * In that case point at the input expression.
1072 * XXX possibly this is more generally useful than coercion errors;
1073 * if so, should rename and place with parser_errposition.
1076 parser_coercion_errposition(ParseState *pstate,
1077 int coerce_location,
1080 if (coerce_location >= 0)
1081 return parser_errposition(pstate, coerce_location);
1083 return parser_errposition(pstate, exprLocation(input_expr));
1088 * select_common_type()
1089 * Determine the common supertype of a list of input expressions.
1090 * This is used for determining the output type of CASE, UNION,
1091 * and similar constructs.
1093 * 'exprs' is a *nonempty* list of expressions. Note that earlier items
1094 * in the list will be preferred if there is doubt.
1095 * 'context' is a phrase to use in the error message if we fail to select
1096 * a usable type. Pass NULL to have the routine return InvalidOid
1097 * rather than throwing an error on failure.
1098 * 'which_expr': if not NULL, receives a pointer to the particular input
1099 * expression from which the result type was taken.
1102 select_common_type(ParseState *pstate, List *exprs, const char *context,
1107 TYPCATEGORY pcategory;
1111 Assert(exprs != NIL);
1112 pexpr = (Node *) linitial(exprs);
1113 lc = lnext(list_head(exprs));
1114 ptype = exprType(pexpr);
1117 * If all input types are valid and exactly the same, just pick that type.
1118 * This is the only way that we will resolve the result as being a domain
1119 * type; otherwise domains are smashed to their base types for comparison.
1121 if (ptype != UNKNOWNOID)
1123 for_each_cell(lc, lc)
1125 Node *nexpr = (Node *) lfirst(lc);
1126 Oid ntype = exprType(nexpr);
1131 if (lc == NULL) /* got to the end of the list? */
1134 *which_expr = pexpr;
1140 * Nope, so set up for the full algorithm. Note that at this point,
1141 * lc points to the first list item with type different from pexpr's;
1142 * we need not re-examine any items the previous loop advanced over.
1144 ptype = getBaseType(ptype);
1145 get_type_category_preferred(ptype, &pcategory, &pispreferred);
1147 for_each_cell(lc, lc)
1149 Node *nexpr = (Node *) lfirst(lc);
1150 Oid ntype = getBaseType(exprType(nexpr));
1152 /* move on to next one if no new information... */
1153 if (ntype != UNKNOWNOID && ntype != ptype)
1155 TYPCATEGORY ncategory;
1158 get_type_category_preferred(ntype, &ncategory, &nispreferred);
1159 if (ptype == UNKNOWNOID)
1161 /* so far, only unknowns so take anything... */
1164 pcategory = ncategory;
1165 pispreferred = nispreferred;
1167 else if (ncategory != pcategory)
1170 * both types in different categories? then not much hope...
1172 if (context == NULL)
1175 (errcode(ERRCODE_DATATYPE_MISMATCH),
1177 translator: first %s is name of a SQL construct, eg CASE */
1178 errmsg("%s types %s and %s cannot be matched",
1180 format_type_be(ptype),
1181 format_type_be(ntype)),
1182 parser_errposition(pstate, exprLocation(nexpr))));
1184 else if (!pispreferred &&
1185 can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1186 !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1189 * take new type if can coerce to it implicitly but not the
1190 * other way; but if we have a preferred type, stay on it.
1194 pcategory = ncategory;
1195 pispreferred = nispreferred;
1201 * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1202 * then resolve as type TEXT. This situation comes up with constructs
1203 * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1204 * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1205 * output type as UNKNOWN, but that really doesn't work, because we'd
1206 * probably end up needing a runtime coercion from UNKNOWN to something
1207 * else, and we usually won't have it. We need to coerce the unknown
1208 * literals while they are still literals, so a decision has to be made
1211 if (ptype == UNKNOWNOID)
1215 *which_expr = pexpr;
1220 * coerce_to_common_type()
1221 * Coerce an expression to the given type.
1223 * This is used following select_common_type() to coerce the individual
1224 * expressions to the desired type. 'context' is a phrase to use in the
1225 * error message if we fail to coerce.
1227 * As with coerce_type, pstate may be NULL if no special unknown-Param
1228 * processing is wanted.
1231 coerce_to_common_type(ParseState *pstate, Node *node,
1232 Oid targetTypeId, const char *context)
1234 Oid inputTypeId = exprType(node);
1236 if (inputTypeId == targetTypeId)
1237 return node; /* no work */
1238 if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
1239 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1240 COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
1243 (errcode(ERRCODE_CANNOT_COERCE),
1244 /* translator: first %s is name of a SQL construct, eg CASE */
1245 errmsg("%s could not convert type %s to %s",
1247 format_type_be(inputTypeId),
1248 format_type_be(targetTypeId)),
1249 parser_errposition(pstate, exprLocation(node))));
1254 * check_generic_type_consistency()
1255 * Are the actual arguments potentially compatible with a
1256 * polymorphic function?
1258 * The argument consistency rules are:
1260 * 1) All arguments declared ANYARRAY must have matching datatypes,
1261 * and must in fact be varlena arrays.
1262 * 2) All arguments declared ANYELEMENT must have matching datatypes.
1263 * 3) If there are arguments of both ANYELEMENT and ANYARRAY, make sure
1264 * the actual ANYELEMENT datatype is in fact the element type for
1265 * the actual ANYARRAY datatype.
1266 * 4) ANYENUM is treated the same as ANYELEMENT except that if it is used
1267 * (alone or in combination with plain ANYELEMENT), we add the extra
1268 * condition that the ANYELEMENT type must be an enum.
1269 * 5) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1270 * we add the extra condition that the ANYELEMENT type must not be an array.
1271 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1272 * is an extra restriction if not.)
1274 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1275 * argument, assume it is okay.
1277 * If an input is of type ANYARRAY (ie, we know it's an array, but not
1278 * what element type), we will accept it as a match to an argument declared
1279 * ANYARRAY, so long as we don't have to determine an element type ---
1280 * that is, so long as there is no use of ANYELEMENT. This is mostly for
1281 * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
1283 * We do not ereport here, but just return FALSE if a rule is violated.
1286 check_generic_type_consistency(Oid *actual_arg_types,
1287 Oid *declared_arg_types,
1291 Oid elem_typeid = InvalidOid;
1292 Oid array_typeid = InvalidOid;
1294 bool have_anyelement = false;
1295 bool have_anynonarray = false;
1296 bool have_anyenum = false;
1299 * Loop through the arguments to see if we have any that are polymorphic.
1300 * If so, require the actual types to be consistent.
1302 for (j = 0; j < nargs; j++)
1304 Oid decl_type = declared_arg_types[j];
1305 Oid actual_type = actual_arg_types[j];
1307 if (decl_type == ANYELEMENTOID ||
1308 decl_type == ANYNONARRAYOID ||
1309 decl_type == ANYENUMOID)
1311 have_anyelement = true;
1312 if (decl_type == ANYNONARRAYOID)
1313 have_anynonarray = true;
1314 else if (decl_type == ANYENUMOID)
1315 have_anyenum = true;
1316 if (actual_type == UNKNOWNOID)
1318 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1320 elem_typeid = actual_type;
1322 else if (decl_type == ANYARRAYOID)
1324 if (actual_type == UNKNOWNOID)
1326 if (OidIsValid(array_typeid) && actual_type != array_typeid)
1328 array_typeid = actual_type;
1332 /* Get the element type based on the array type, if we have one */
1333 if (OidIsValid(array_typeid))
1335 if (array_typeid == ANYARRAYOID)
1337 /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1338 if (have_anyelement)
1343 array_typelem = get_element_type(array_typeid);
1344 if (!OidIsValid(array_typelem))
1345 return false; /* should be an array, but isn't */
1347 if (!OidIsValid(elem_typeid))
1350 * if we don't have an element type yet, use the one we just got
1352 elem_typeid = array_typelem;
1354 else if (array_typelem != elem_typeid)
1356 /* otherwise, they better match */
1361 if (have_anynonarray)
1363 /* require the element type to not be an array */
1364 if (type_is_array(elem_typeid))
1370 /* require the element type to be an enum */
1371 if (!type_is_enum(elem_typeid))
1380 * enforce_generic_type_consistency()
1381 * Make sure a polymorphic function is legally callable, and
1382 * deduce actual argument and result types.
1384 * If any polymorphic pseudotype is used in a function's arguments or
1385 * return type, we make sure the actual data types are consistent with
1386 * each other. The argument consistency rules are shown above for
1387 * check_generic_type_consistency().
1389 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1390 * argument, we attempt to deduce the actual type it should have. If
1391 * successful, we alter that position of declared_arg_types[] so that
1392 * make_fn_arguments will coerce the literal to the right thing.
1394 * Rules are applied to the function's return type (possibly altering it)
1395 * if it is declared as a polymorphic type:
1397 * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1398 * argument's actual type as the function's return type.
1399 * 2) If return type is ANYARRAY, no argument is ANYARRAY, but any argument
1400 * is ANYELEMENT, use the actual type of the argument to determine
1401 * the function's return type, i.e. the element type's corresponding
1403 * 3) If return type is ANYARRAY, no argument is ANYARRAY or ANYELEMENT,
1404 * generate an ERROR. This condition is prevented by CREATE FUNCTION
1405 * and is therefore not expected here.
1406 * 4) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1407 * argument's actual type as the function's return type.
1408 * 5) If return type is ANYELEMENT, no argument is ANYELEMENT, but any
1409 * argument is ANYARRAY, use the actual type of the argument to determine
1410 * the function's return type, i.e. the array type's corresponding
1412 * 6) If return type is ANYELEMENT, no argument is ANYARRAY or ANYELEMENT,
1413 * generate an ERROR. This condition is prevented by CREATE FUNCTION
1414 * and is therefore not expected here.
1415 * 7) ANYENUM is treated the same as ANYELEMENT except that if it is used
1416 * (alone or in combination with plain ANYELEMENT), we add the extra
1417 * condition that the ANYELEMENT type must be an enum.
1418 * 8) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1419 * we add the extra condition that the ANYELEMENT type must not be an array.
1420 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1421 * is an extra restriction if not.)
1423 * When allow_poly is false, we are not expecting any of the actual_arg_types
1424 * to be polymorphic, and we should not return a polymorphic result type
1425 * either. When allow_poly is true, it is okay to have polymorphic "actual"
1426 * arg types, and we can return ANYARRAY or ANYELEMENT as the result. (This
1427 * case is currently used only to check compatibility of an aggregate's
1428 * declaration with the underlying transfn.)
1430 * A special case is that we could see ANYARRAY as an actual_arg_type even
1431 * when allow_poly is false (this is possible only because pg_statistic has
1432 * columns shown as anyarray in the catalogs). We allow this to match a
1433 * declared ANYARRAY argument, but only if there is no ANYELEMENT argument
1434 * or result (since we can't determine a specific element type to match to
1435 * ANYELEMENT). Note this means that functions taking ANYARRAY had better
1436 * behave sanely if applied to the pg_statistic columns; they can't just
1437 * assume that successive inputs are of the same actual element type.
1440 enforce_generic_type_consistency(Oid *actual_arg_types,
1441 Oid *declared_arg_types,
1447 bool have_generics = false;
1448 bool have_unknowns = false;
1449 Oid elem_typeid = InvalidOid;
1450 Oid array_typeid = InvalidOid;
1452 bool have_anyelement = (rettype == ANYELEMENTOID ||
1453 rettype == ANYNONARRAYOID ||
1454 rettype == ANYENUMOID);
1455 bool have_anynonarray = (rettype == ANYNONARRAYOID);
1456 bool have_anyenum = (rettype == ANYENUMOID);
1459 * Loop through the arguments to see if we have any that are polymorphic.
1460 * If so, require the actual types to be consistent.
1462 for (j = 0; j < nargs; j++)
1464 Oid decl_type = declared_arg_types[j];
1465 Oid actual_type = actual_arg_types[j];
1467 if (decl_type == ANYELEMENTOID ||
1468 decl_type == ANYNONARRAYOID ||
1469 decl_type == ANYENUMOID)
1471 have_generics = have_anyelement = true;
1472 if (decl_type == ANYNONARRAYOID)
1473 have_anynonarray = true;
1474 else if (decl_type == ANYENUMOID)
1475 have_anyenum = true;
1476 if (actual_type == UNKNOWNOID)
1478 have_unknowns = true;
1481 if (allow_poly && decl_type == actual_type)
1482 continue; /* no new information here */
1483 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1485 (errcode(ERRCODE_DATATYPE_MISMATCH),
1486 errmsg("arguments declared \"anyelement\" are not all alike"),
1487 errdetail("%s versus %s",
1488 format_type_be(elem_typeid),
1489 format_type_be(actual_type))));
1490 elem_typeid = actual_type;
1492 else if (decl_type == ANYARRAYOID)
1494 have_generics = true;
1495 if (actual_type == UNKNOWNOID)
1497 have_unknowns = true;
1500 if (allow_poly && decl_type == actual_type)
1501 continue; /* no new information here */
1502 if (OidIsValid(array_typeid) && actual_type != array_typeid)
1504 (errcode(ERRCODE_DATATYPE_MISMATCH),
1505 errmsg("arguments declared \"anyarray\" are not all alike"),
1506 errdetail("%s versus %s",
1507 format_type_be(array_typeid),
1508 format_type_be(actual_type))));
1509 array_typeid = actual_type;
1514 * Fast Track: if none of the arguments are polymorphic, return the
1515 * unmodified rettype. We assume it can't be polymorphic either.
1520 /* Get the element type based on the array type, if we have one */
1521 if (OidIsValid(array_typeid))
1523 if (array_typeid == ANYARRAYOID && !have_anyelement)
1525 /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1526 array_typelem = InvalidOid;
1530 array_typelem = get_element_type(array_typeid);
1531 if (!OidIsValid(array_typelem))
1533 (errcode(ERRCODE_DATATYPE_MISMATCH),
1534 errmsg("argument declared \"anyarray\" is not an array but type %s",
1535 format_type_be(array_typeid))));
1538 if (!OidIsValid(elem_typeid))
1541 * if we don't have an element type yet, use the one we just got
1543 elem_typeid = array_typelem;
1545 else if (array_typelem != elem_typeid)
1547 /* otherwise, they better match */
1549 (errcode(ERRCODE_DATATYPE_MISMATCH),
1550 errmsg("argument declared \"anyarray\" is not consistent with argument declared \"anyelement\""),
1551 errdetail("%s versus %s",
1552 format_type_be(array_typeid),
1553 format_type_be(elem_typeid))));
1556 else if (!OidIsValid(elem_typeid))
1560 array_typeid = ANYARRAYOID;
1561 elem_typeid = ANYELEMENTOID;
1565 /* Only way to get here is if all the generic args are UNKNOWN */
1567 (errcode(ERRCODE_DATATYPE_MISMATCH),
1568 errmsg("could not determine polymorphic type because input has type \"unknown\"")));
1572 if (have_anynonarray && elem_typeid != ANYELEMENTOID)
1574 /* require the element type to not be an array */
1575 if (type_is_array(elem_typeid))
1577 (errcode(ERRCODE_DATATYPE_MISMATCH),
1578 errmsg("type matched to anynonarray is an array type: %s",
1579 format_type_be(elem_typeid))));
1582 if (have_anyenum && elem_typeid != ANYELEMENTOID)
1584 /* require the element type to be an enum */
1585 if (!type_is_enum(elem_typeid))
1587 (errcode(ERRCODE_DATATYPE_MISMATCH),
1588 errmsg("type matched to anyenum is not an enum type: %s",
1589 format_type_be(elem_typeid))));
1593 * If we had any unknown inputs, re-scan to assign correct types
1597 for (j = 0; j < nargs; j++)
1599 Oid decl_type = declared_arg_types[j];
1600 Oid actual_type = actual_arg_types[j];
1602 if (actual_type != UNKNOWNOID)
1605 if (decl_type == ANYELEMENTOID ||
1606 decl_type == ANYNONARRAYOID ||
1607 decl_type == ANYENUMOID)
1608 declared_arg_types[j] = elem_typeid;
1609 else if (decl_type == ANYARRAYOID)
1611 if (!OidIsValid(array_typeid))
1613 array_typeid = get_array_type(elem_typeid);
1614 if (!OidIsValid(array_typeid))
1616 (errcode(ERRCODE_UNDEFINED_OBJECT),
1617 errmsg("could not find array type for data type %s",
1618 format_type_be(elem_typeid))));
1620 declared_arg_types[j] = array_typeid;
1625 /* if we return ANYARRAY use the appropriate argument type */
1626 if (rettype == ANYARRAYOID)
1628 if (!OidIsValid(array_typeid))
1630 array_typeid = get_array_type(elem_typeid);
1631 if (!OidIsValid(array_typeid))
1633 (errcode(ERRCODE_UNDEFINED_OBJECT),
1634 errmsg("could not find array type for data type %s",
1635 format_type_be(elem_typeid))));
1637 return array_typeid;
1640 /* if we return ANYELEMENT use the appropriate argument type */
1641 if (rettype == ANYELEMENTOID ||
1642 rettype == ANYNONARRAYOID ||
1643 rettype == ANYENUMOID)
1646 /* we don't return a generic type; send back the original return type */
1651 * resolve_generic_type()
1652 * Deduce an individual actual datatype on the assumption that
1653 * the rules for polymorphic types are being followed.
1655 * declared_type is the declared datatype we want to resolve.
1656 * context_actual_type is the actual input datatype to some argument
1657 * that has declared datatype context_declared_type.
1659 * If declared_type isn't polymorphic, we just return it. Otherwise,
1660 * context_declared_type must be polymorphic, and we deduce the correct
1661 * return type based on the relationship of the two polymorphic types.
1664 resolve_generic_type(Oid declared_type,
1665 Oid context_actual_type,
1666 Oid context_declared_type)
1668 if (declared_type == ANYARRAYOID)
1670 if (context_declared_type == ANYARRAYOID)
1672 /* Use actual type, but it must be an array */
1673 Oid array_typelem = get_element_type(context_actual_type);
1675 if (!OidIsValid(array_typelem))
1677 (errcode(ERRCODE_DATATYPE_MISMATCH),
1678 errmsg("argument declared \"anyarray\" is not an array but type %s",
1679 format_type_be(context_actual_type))));
1680 return context_actual_type;
1682 else if (context_declared_type == ANYELEMENTOID ||
1683 context_declared_type == ANYNONARRAYOID ||
1684 context_declared_type == ANYENUMOID)
1686 /* Use the array type corresponding to actual type */
1687 Oid array_typeid = get_array_type(context_actual_type);
1689 if (!OidIsValid(array_typeid))
1691 (errcode(ERRCODE_UNDEFINED_OBJECT),
1692 errmsg("could not find array type for data type %s",
1693 format_type_be(context_actual_type))));
1694 return array_typeid;
1697 else if (declared_type == ANYELEMENTOID ||
1698 declared_type == ANYNONARRAYOID ||
1699 declared_type == ANYENUMOID)
1701 if (context_declared_type == ANYARRAYOID)
1703 /* Use the element type corresponding to actual type */
1704 Oid array_typelem = get_element_type(context_actual_type);
1706 if (!OidIsValid(array_typelem))
1708 (errcode(ERRCODE_DATATYPE_MISMATCH),
1709 errmsg("argument declared \"anyarray\" is not an array but type %s",
1710 format_type_be(context_actual_type))));
1711 return array_typelem;
1713 else if (context_declared_type == ANYELEMENTOID ||
1714 context_declared_type == ANYNONARRAYOID ||
1715 context_declared_type == ANYENUMOID)
1717 /* Use the actual type; it doesn't matter if array or not */
1718 return context_actual_type;
1723 /* declared_type isn't polymorphic, so return it as-is */
1724 return declared_type;
1726 /* If we get here, declared_type is polymorphic and context isn't */
1727 /* NB: this is a calling-code logic error, not a user error */
1728 elog(ERROR, "could not determine polymorphic type because context isn't polymorphic");
1729 return InvalidOid; /* keep compiler quiet */
1734 * Assign a category to the specified type OID.
1736 * NB: this must not return TYPCATEGORY_INVALID.
1739 TypeCategory(Oid type)
1742 bool typispreferred;
1744 get_type_category_preferred(type, &typcategory, &typispreferred);
1745 Assert(typcategory != TYPCATEGORY_INVALID);
1746 return (TYPCATEGORY) typcategory;
1750 /* IsPreferredType()
1751 * Check if this type is a preferred type for the given category.
1753 * If category is TYPCATEGORY_INVALID, then we'll return TRUE for preferred
1754 * types of any category; otherwise, only for preferred types of that
1758 IsPreferredType(TYPCATEGORY category, Oid type)
1761 bool typispreferred;
1763 get_type_category_preferred(type, &typcategory, &typispreferred);
1764 if (category == typcategory || category == TYPCATEGORY_INVALID)
1765 return typispreferred;
1771 /* IsBinaryCoercible()
1772 * Check if srctype is binary-coercible to targettype.
1774 * This notion allows us to cheat and directly exchange values without
1775 * going through the trouble of calling a conversion function. Note that
1776 * in general, this should only be an implementation shortcut. Before 7.4,
1777 * this was also used as a heuristic for resolving overloaded functions and
1778 * operators, but that's basically a bad idea.
1780 * As of 7.3, binary coercibility isn't hardwired into the code anymore.
1781 * We consider two types binary-coercible if there is an implicitly
1782 * invokable, no-function-needed pg_cast entry. Also, a domain is always
1783 * binary-coercible to its base type, though *not* vice versa (in the other
1784 * direction, one must apply domain constraint checks before accepting the
1785 * value as legitimate). We also need to special-case various polymorphic
1788 * This function replaces IsBinaryCompatible(), which was an inherently
1789 * symmetric test. Since the pg_cast entries aren't necessarily symmetric,
1790 * the order of the operands is now significant.
1793 IsBinaryCoercible(Oid srctype, Oid targettype)
1796 Form_pg_cast castForm;
1799 /* Fast path if same type */
1800 if (srctype == targettype)
1803 /* If srctype is a domain, reduce to its base type */
1804 if (OidIsValid(srctype))
1805 srctype = getBaseType(srctype);
1807 /* Somewhat-fast path for domain -> base type case */
1808 if (srctype == targettype)
1811 /* Also accept any array type as coercible to ANYARRAY */
1812 if (targettype == ANYARRAYOID)
1813 if (type_is_array(srctype))
1816 /* Also accept any non-array type as coercible to ANYNONARRAY */
1817 if (targettype == ANYNONARRAYOID)
1818 if (!type_is_array(srctype))
1821 /* Also accept any enum type as coercible to ANYENUM */
1822 if (targettype == ANYENUMOID)
1823 if (type_is_enum(srctype))
1826 /* Also accept any composite type as coercible to RECORD */
1827 if (targettype == RECORDOID)
1828 if (ISCOMPLEX(srctype))
1831 /* Also accept any composite array type as coercible to RECORD[] */
1832 if (targettype == RECORDARRAYOID)
1833 if (is_complex_array(srctype))
1836 /* Else look in pg_cast */
1837 tuple = SearchSysCache(CASTSOURCETARGET,
1838 ObjectIdGetDatum(srctype),
1839 ObjectIdGetDatum(targettype),
1841 if (!HeapTupleIsValid(tuple))
1842 return false; /* no cast */
1843 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1845 result = (castForm->castfunc == InvalidOid &&
1846 castForm->castcontext == COERCION_CODE_IMPLICIT);
1848 ReleaseSysCache(tuple);
1855 * find_coercion_pathway
1856 * Look for a coercion pathway between two types.
1858 * Currently, this deals only with scalar-type cases; it does not consider
1859 * polymorphic types nor casts between composite types. (Perhaps fold
1860 * those in someday?)
1862 * ccontext determines the set of available casts.
1864 * The possible result codes are:
1865 * COERCION_PATH_NONE: failed to find any coercion pathway
1866 * *funcid is set to InvalidOid
1867 * COERCION_PATH_FUNC: apply the coercion function returned in *funcid
1868 * COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
1869 * *funcid is set to InvalidOid
1870 * COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
1871 * *funcid is set to the element cast function, or InvalidOid
1872 * if the array elements are binary-compatible
1873 * COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
1874 * *funcid is set to InvalidOid
1876 * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
1877 * needed to do the coercion; if the target is a domain then we may need to
1878 * apply domain constraint checking. If you want to check for a zero-effort
1879 * conversion then use IsBinaryCoercible().
1882 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
1883 CoercionContext ccontext,
1886 CoercionPathType result = COERCION_PATH_NONE;
1889 *funcid = InvalidOid;
1891 /* Perhaps the types are domains; if so, look at their base types */
1892 if (OidIsValid(sourceTypeId))
1893 sourceTypeId = getBaseType(sourceTypeId);
1894 if (OidIsValid(targetTypeId))
1895 targetTypeId = getBaseType(targetTypeId);
1897 /* Domains are always coercible to and from their base type */
1898 if (sourceTypeId == targetTypeId)
1899 return COERCION_PATH_RELABELTYPE;
1901 /* Look in pg_cast */
1902 tuple = SearchSysCache(CASTSOURCETARGET,
1903 ObjectIdGetDatum(sourceTypeId),
1904 ObjectIdGetDatum(targetTypeId),
1907 if (HeapTupleIsValid(tuple))
1909 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1910 CoercionContext castcontext;
1912 /* convert char value for castcontext to CoercionContext enum */
1913 switch (castForm->castcontext)
1915 case COERCION_CODE_IMPLICIT:
1916 castcontext = COERCION_IMPLICIT;
1918 case COERCION_CODE_ASSIGNMENT:
1919 castcontext = COERCION_ASSIGNMENT;
1921 case COERCION_CODE_EXPLICIT:
1922 castcontext = COERCION_EXPLICIT;
1925 elog(ERROR, "unrecognized castcontext: %d",
1926 (int) castForm->castcontext);
1927 castcontext = 0; /* keep compiler quiet */
1931 /* Rely on ordering of enum for correct behavior here */
1932 if (ccontext >= castcontext)
1934 switch (castForm->castmethod)
1936 case COERCION_METHOD_FUNCTION:
1937 result = COERCION_PATH_FUNC;
1938 *funcid = castForm->castfunc;
1940 case COERCION_METHOD_INOUT:
1941 result = COERCION_PATH_COERCEVIAIO;
1943 case COERCION_METHOD_BINARY:
1944 result = COERCION_PATH_RELABELTYPE;
1947 elog(ERROR, "unrecognized castmethod: %d",
1948 (int) castForm->castmethod);
1953 ReleaseSysCache(tuple);
1958 * If there's no pg_cast entry, perhaps we are dealing with a pair of
1959 * array types. If so, and if the element types have a suitable cast,
1960 * report that we can coerce with an ArrayCoerceExpr.
1962 * Hack: disallow coercions to oidvector and int2vector, which
1963 * otherwise tend to capture coercions that should go to "real" array
1964 * types. We want those types to be considered "real" arrays for many
1965 * purposes, but not this one. (Also, ArrayCoerceExpr isn't
1966 * guaranteed to produce an output that meets the restrictions of
1967 * these datatypes, such as being 1-dimensional.)
1969 if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
1974 if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
1975 (sourceElem = get_element_type(sourceTypeId)) != InvalidOid)
1977 CoercionPathType elempathtype;
1980 elempathtype = find_coercion_pathway(targetElem,
1984 if (elempathtype != COERCION_PATH_NONE &&
1985 elempathtype != COERCION_PATH_ARRAYCOERCE)
1987 *funcid = elemfuncid;
1988 if (elempathtype == COERCION_PATH_COERCEVIAIO)
1989 result = COERCION_PATH_COERCEVIAIO;
1991 result = COERCION_PATH_ARRAYCOERCE;
1997 * If we still haven't found a possibility, consider automatic casting
1998 * using I/O functions. We allow assignment casts to string types
1999 * and explicit casts from string types to be handled this way. (The
2000 * CoerceViaIO mechanism is a lot more general than that, but this is
2001 * all we want to allow in the absence of a pg_cast entry.) It would
2002 * probably be better to insist on explicit casts in both directions,
2003 * but this is a compromise to preserve something of the pre-8.3
2004 * behavior that many types had implicit (yipes!) casts to text.
2006 if (result == COERCION_PATH_NONE)
2008 if (ccontext >= COERCION_ASSIGNMENT &&
2009 TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
2010 result = COERCION_PATH_COERCEVIAIO;
2011 else if (ccontext >= COERCION_EXPLICIT &&
2012 TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
2013 result = COERCION_PATH_COERCEVIAIO;
2022 * find_typmod_coercion_function -- does the given type need length coercion?
2024 * If the target type possesses a pg_cast function from itself to itself,
2025 * it must need length coercion.
2027 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
2029 * If the given type is a varlena array type, we do not look for a coercion
2030 * function associated directly with the array type, but instead look for
2031 * one associated with the element type. An ArrayCoerceExpr node must be
2032 * used to apply such a function.
2034 * We use the same result enum as find_coercion_pathway, but the only possible
2036 * COERCION_PATH_NONE: no length coercion needed
2037 * COERCION_PATH_FUNC: apply the function returned in *funcid
2038 * COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
2041 find_typmod_coercion_function(Oid typeId,
2044 CoercionPathType result;
2046 Form_pg_type typeForm;
2049 *funcid = InvalidOid;
2050 result = COERCION_PATH_FUNC;
2052 targetType = typeidType(typeId);
2053 typeForm = (Form_pg_type) GETSTRUCT(targetType);
2055 /* Check for a varlena array type (and not a domain) */
2056 if (typeForm->typelem != InvalidOid &&
2057 typeForm->typlen == -1 &&
2058 typeForm->typtype != TYPTYPE_DOMAIN)
2060 /* Yes, switch our attention to the element type */
2061 typeId = typeForm->typelem;
2062 result = COERCION_PATH_ARRAYCOERCE;
2064 ReleaseSysCache(targetType);
2066 /* Look in pg_cast */
2067 tuple = SearchSysCache(CASTSOURCETARGET,
2068 ObjectIdGetDatum(typeId),
2069 ObjectIdGetDatum(typeId),
2072 if (HeapTupleIsValid(tuple))
2074 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2076 *funcid = castForm->castfunc;
2077 ReleaseSysCache(tuple);
2080 if (!OidIsValid(*funcid))
2081 result = COERCION_PATH_NONE;
2088 * Is this type an array of composite?
2090 * Note: this will not return true for record[]; check for RECORDARRAYOID
2091 * separately if needed.
2094 is_complex_array(Oid typid)
2096 Oid elemtype = get_element_type(typid);
2098 return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));