1/*-------------------------------------------------------------------------
4 * handle type coercions/conversions for parser
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/parser/parse_coerce.c
13 *-------------------------------------------------------------------------
30#include "utils/fmgroids.h"
37 Oid targetTypeId,
int32 targetTypMod,
40 bool hideInputCoercion);
45 Oid targetTypeId,
int32 targetTypMod,
58 * coerce_to_target_type()
59 * Convert an expression to a target type and typmod.
61 * This is the general-purpose entry point for arbitrary type coercion
62 * operations. Direct use of the component operations can_coerce_type,
63 * coerce_type, and coerce_type_typmod should be restricted to special
64 * cases (eg, when the conversion is expected to succeed).
66 * Returns the possibly-transformed expression tree, or NULL if the type
67 * conversion is not possible. (We do this, rather than ereport'ing directly,
68 * so that callers can generate custom error messages indicating context.)
70 * pstate - parse state (can be NULL, see coerce_type)
71 * expr - input expression tree (already transformed by transformExpr)
72 * exprtype - result type of expr
73 * targettype - desired result type
74 * targettypmod - desired result typmod
75 * ccontext, cformat - context indicators to control coercions
76 * location - parse location of the coercion request, or -1 if unknown/implicit
92 * If the input has a CollateExpr at the top, strip it off, perform the
93 * coercion, and put a new one back on. This is annoying since it
94 * duplicates logic in coerce_type, but if we don't do this then it's too
95 * hard to tell whether coerce_type actually changed anything, and we
96 * *must* know that to avoid possibly calling hide_coercion_node on
97 * something that wasn't generated by coerce_type. Note that if there are
98 * multiple stacked CollateExprs, we just discard all but the topmost.
99 * Also, if the target type isn't collatable, we discard the CollateExpr.
106 targettype, targettypmod,
107 ccontext, cformat, location);
110 * If the target is a fixed-length type, it may need a length coercion as
111 * well as a type coercion. If we find ourselves adding both, force the
112 * inner coercion node to implicit display form.
115 targettype, targettypmod,
116 ccontext, cformat, location,
117 (result != expr && !
IsA(result,
Const)));
121 /* Reinstall top CollateExpr */
125 newcoll->
arg = (
Expr *) result;
128 result = (
Node *) newcoll;
137 * Convert an expression to a different type.
139 * The caller should already have determined that the coercion is possible;
140 * see can_coerce_type.
142 * Normally, no coercion to a typmod (length) is performed here. The caller
143 * must call coerce_type_typmod as well, if a typmod constraint is wanted.
144 * (But if the target type is a domain, it may internally contain a
145 * typmod constraint, which will be applied inside coerce_to_domain.)
146 * In some cases pg_cast specifies a type coercion function that also
147 * applies length conversion, and in those cases only, the result will
148 * already be properly coerced to the specified typmod.
150 * pstate is only used in the case that we are able to resolve the type of
151 * a previously UNKNOWN Param. It is okay to pass pstate = NULL if the
152 * caller does not want type information updated for Params.
154 * Note: this function must not modify the given expression tree, only add
155 * decoration on top of it. See transformSetOperationTree, for example.
159 Oid inputTypeId,
Oid targetTypeId,
int32 targetTypeMod,
166 if (targetTypeId == inputTypeId ||
169 /* no conversion needed */
172 if (targetTypeId == ANYOID ||
173 targetTypeId == ANYELEMENTOID ||
174 targetTypeId == ANYNONARRAYOID ||
175 targetTypeId == ANYCOMPATIBLEOID ||
176 targetTypeId == ANYCOMPATIBLENONARRAYOID)
179 * Assume can_coerce_type verified that implicit coercion is okay.
181 * Note: by returning the unmodified node here, we are saying that
182 * it's OK to treat an UNKNOWN constant as a valid input for a
183 * function accepting one of these pseudotypes. This should be all
184 * right, since an UNKNOWN value is still a perfectly valid Datum.
186 * NB: we do NOT want a RelabelType here: the exposed type of the
187 * function argument must be its actual type, not the polymorphic
192 if (targetTypeId == ANYARRAYOID ||
193 targetTypeId == ANYENUMOID ||
194 targetTypeId == ANYRANGEOID ||
195 targetTypeId == ANYMULTIRANGEOID ||
196 targetTypeId == ANYCOMPATIBLEARRAYOID ||
197 targetTypeId == ANYCOMPATIBLERANGEOID ||
198 targetTypeId == ANYCOMPATIBLEMULTIRANGEOID)
201 * Assume can_coerce_type verified that implicit coercion is okay.
203 * These cases are unlike the ones above because the exposed type of
204 * the argument must be an actual array, enum, range, or multirange
205 * type. In particular the argument must *not* be an UNKNOWN
206 * constant. If it is, we just fall through; below, we'll call the
207 * pseudotype's input function, which will produce an error. Also, if
208 * what we have is a domain over array, enum, range, or multirange, we
209 * have to relabel it to its base type.
211 * Note: currently, we can't actually see a domain-over-enum here,
212 * since the other functions in this file will not match such a
213 * parameter to ANYENUM. But that should get changed eventually.
215 if (inputTypeId != UNKNOWNOID)
219 if (baseTypeId != inputTypeId)
229 /* Not a domain type, so return it as-is */
233 if (inputTypeId == UNKNOWNOID &&
IsA(node,
Const))
236 * Input is a string constant with previously undetermined type. Apply
237 * the target type's typinput function to it to produce a constant of
240 * NOTE: this case cannot be folded together with the other
241 * constant-input case, since the typinput function does not
242 * necessarily behave the same as a type conversion function. For
243 * example, int4's typinput function will reject "1.2", whereas
244 * float-to-int type conversion will round to integer.
246 * XXX if the typinput function is not immutable, we really ought to
247 * postpone evaluation of the function call until runtime. But there
248 * is no way to represent a typinput function call as an expression
249 * tree, because C-string values are not Datums. (XXX This *is*
250 * possible as of 7.3, do we want to do it?)
261 * If the target type is a domain, we want to call its base type's
262 * input routine, not domain_in(). This is to avoid premature failure
263 * when the domain applies a typmod: existing input routines follow
264 * implicit-coercion semantics for length checks, which is not always
265 * what we want here. The needed check will be applied properly
266 * inside coerce_to_domain().
268 baseTypeMod = targetTypeMod;
272 * For most types we pass typmod -1 to the input routine, because
273 * existing input routines follow implicit-coercion semantics for
274 * length checks, which is not always what we want here. Any length
275 * constraint will be applied later by our caller. An exception
276 * however is the INTERVAL type, for which we *must* pass the typmod
277 * or it won't be able to obey the bizarre SQL-spec input rules. (Ugly
278 * as sin, but so is this part of the spec...)
280 if (baseTypeId == INTERVALOID)
281 inputTypeMod = baseTypeMod;
288 newcon->consttypmod = inputTypeMod;
290 newcon->constlen =
typeLen(baseType);
291 newcon->constbyval =
typeByVal(baseType);
292 newcon->constisnull = con->constisnull;
295 * We use the original literal's location regardless of the position
296 * of the coercion. This is a change from pre-9.2 behavior, meant to
297 * simplify life for pg_stat_statements.
299 newcon->location = con->location;
302 * Set up to point at the constant's text if the input routine throws
308 * We assume here that UNKNOWN's internal representation is the same
311 if (!con->constisnull)
321 * If it's a varlena value, force it to be in non-expanded
322 * (non-toasted) format; this avoids any possible dependency on
323 * external values and improves consistency of representation.
325 if (!con->constisnull && newcon->constlen == -1)
329#ifdef RANDOMIZE_ALLOCATED_MEMORY
332 * For pass-by-reference data types, repeat the conversion to see if
333 * the input function leaves any uninitialized bytes in the result. We
334 * can only detect that reliably if RANDOMIZE_ALLOCATED_MEMORY is
335 * enabled, so we don't bother testing otherwise. The reason we don't
336 * want any instability in the input function is that comparison of
337 * Const nodes relies on bytewise comparison of the datums, so if the
338 * input function leaves garbage then subexpressions that should be
339 * identical may not get recognized as such. See pgsql-hackers
340 * discussion of 2008年04月04日.
342 if (!con->constisnull && !newcon->constbyval)
349 if (newcon->constlen == -1)
351 if (!
datumIsEqual(newcon->constvalue, val2,
false, newcon->constlen))
352 elog(
WARNING,
"type %s has unstable input conversion for \"%s\"",
359 result = (
Node *) newcon;
361 /* If target is a domain, apply constraints. */
362 if (baseTypeId != targetTypeId)
364 baseTypeId, baseTypeMod,
366 ccontext, cformat, location,
377 * Allow the CoerceParamHook to decide what happens. It can return a
378 * transformed node (very possibly the same Param node), or return
379 * NULL to indicate we should proceed with normal coercion.
392 * If we have a COLLATE clause, we have to push the coercion
393 * underneath the COLLATE; or discard the COLLATE if the target type
394 * isn't collatable. This is really ugly, but there is little choice
395 * because the above hacks on Consts and Params wouldn't happen
396 * otherwise. This kluge has consequences in coerce_to_target_type.
401 inputTypeId, targetTypeId, targetTypeMod,
402 ccontext, cformat, location);
407 newcoll->
arg = (
Expr *) result;
410 result = (
Node *) newcoll;
421 baseTypeMod = targetTypeMod;
427 * Generate an expression tree representing run-time application
428 * of the conversion function. If we are dealing with a domain
429 * target type, the conversion function will yield the base type,
430 * and we need to extract the correct typmod to use from the
431 * domain's typtypmod.
434 baseTypeId, baseTypeMod,
435 ccontext, cformat, location);
438 * If domain, coerce to the domain type and relabel with domain
439 * type ID, hiding the previous coercion node.
441 if (targetTypeId != baseTypeId)
444 ccontext, cformat, location,
450 * We don't need to do a physical conversion, but we do need to
451 * attach a RelabelType node so that the expression will be seen
452 * to have the intended type when inspected by higher-level code.
454 * Also, domains may have value restrictions beyond the base type
455 * that must be accounted for. If the destination is a domain
456 * then we won't need a RelabelType node.
460 ccontext, cformat, location,
465 * XXX could we label result with exprTypmod(node) instead of
466 * default -1 typmod, to save a possible length-coercion
467 * later? Would work if both types have same interpretation of
468 * typmod, which is likely but not certain.
481 if (inputTypeId == RECORDOID &&
484 /* Coerce a RECORD to a specific complex type */
486 ccontext, cformat, location);
488 if (targetTypeId == RECORDOID &&
491 /* Coerce a specific complex type to RECORD */
492 /* NB: we do NOT want a RelabelType here */
496 if (inputTypeId == RECORDARRAYOID &&
499 /* Coerce record[] to a specific complex array type */
500 /* not implemented yet ... */
503 if (targetTypeId == RECORDARRAYOID &&
506 /* Coerce a specific complex array type to record[] */
507 /* NB: we do NOT want a RelabelType here */
514 * Input class type is a subclass of target, so generate an
515 * appropriate runtime conversion (removing unneeded columns and
516 * possibly rearranging the ones that are wanted).
518 * We will also get here when the input is a domain over a subclass of
519 * the target type. To keep life simple for the executor, we define
520 * ConvertRowtypeExpr as only working between regular composite types;
521 * therefore, in such cases insert a RelabelType to smash the input
522 * expression down to its base type.
527 if (baseTypeId != inputTypeId)
539 r->convertformat = cformat;
543 /* If we get here, caller blew it */
544 elog(
ERROR,
"failed to find conversion function from %s to %s",
546 return NULL;
/* keep compiler quiet */
552 * Can input_typeids be coerced to target_typeids?
554 * We must be told the context (CAST construct, assignment, implicit coercion)
555 * as this determines the set of available casts.
561 bool have_generics =
false;
564 /* run through argument list... */
565 for (
i = 0;
i < nargs;
i++)
567 Oid inputTypeId = input_typeids[
i];
568 Oid targetTypeId = target_typeids[
i];
572 /* no problem if same type */
573 if (inputTypeId == targetTypeId)
576 /* accept if target is ANY */
577 if (targetTypeId == ANYOID)
580 /* accept if target is polymorphic, for now */
581 if (IsPolymorphicType(targetTypeId))
583 have_generics =
true;
/* do more checking later */
588 * If input is an untyped string constant, assume we can convert it to
591 if (inputTypeId == UNKNOWNOID)
595 * If pg_cast shows that we can coerce, accept. This test now covers
596 * both binary-compatible and coercion-function cases.
604 * If input is RECORD and target is a composite type, assume we can
605 * coerce (may need tighter checking here)
607 if (inputTypeId == RECORDOID &&
612 * If input is a composite type and target is RECORD, accept
614 if (targetTypeId == RECORDOID &&
618#ifdef NOT_USED /* not implemented yet */
621 * If input is record[] and target is a composite array type, assume
622 * we can coerce (may need tighter checking here)
624 if (inputTypeId == RECORDARRAYOID &&
630 * If input is a composite array type and target is record[], accept
632 if (targetTypeId == RECORDARRAYOID &&
637 * If input is a class type that inherits from target, accept
644 * Else, cannot coerce at this argument position
649 /* If we found any generic argument types, cross-check them */
662 * Create an expression tree to represent coercion to a domain type.
664 * 'arg': input expression
665 * 'baseTypeId': base type of domain
666 * 'baseTypeMod': base type typmod of domain
667 * 'typeId': target type to coerce to
668 * 'ccontext': context indicator to control coercions
669 * 'cformat': coercion display format
670 * 'location': coercion request location
671 * 'hideInputCoercion': if true, hide the input coercion under this one.
673 * If the target type isn't a domain, the given 'arg' is returned as-is.
678 bool hideInputCoercion)
682 /* We now require the caller to supply correct baseTypeId/baseTypeMod */
685 /* If it isn't a domain, return the node as it was passed in */
686 if (baseTypeId == typeId)
689 /* Suppress display of nested coercion steps */
690 if (hideInputCoercion)
694 * If the domain applies a typmod to its base type, build the appropriate
695 * coercion step. Mark it implicit for display purposes, because we don't
696 * want it shown separately by ruleutils.c; but the isExplicit flag passed
697 * to the conversion function depends on the manner in which the domain
698 * coercion is invoked, so that the semantics of implicit and explicit
699 * coercion differ. (Is that really the behavior we want?)
701 * NOTE: because we apply this as part of the fixed expression structure,
702 * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that that
703 * would be safe to do anyway, without lots of knowledge about what the
704 * base type thinks the typmod means.
711 * Now build the domain coercion node. This represents run-time checking
712 * of any constraints currently attached to the domain. This also ensures
713 * that the expression is properly labeled as to result type.
718 result->resulttypmod = -1;
/* currently, always -1 for domains */
719 /* resultcollid will be set by parse_collate.c */
720 result->coercionformat = cformat;
723 return (
Node *) result;
728 * coerce_type_typmod()
729 * Force a value to a particular typmod, if meaningful and possible.
731 * This is applied to values that are going to be stored in a relation
732 * (where we have an atttypmod for the column) as well as values being
733 * explicitly CASTed (where the typmod comes from the target type spec).
735 * The caller must have already ensured that the value is of the correct
736 * type, typically by applying coerce_type.
738 * ccontext may affect semantics, depending on whether the length coercion
739 * function pays attention to the isExplicit flag it's passed.
741 * cformat determines the display properties of the generated node (if any).
743 * If hideInputCoercion is true *and* we generate a node, the input node is
744 * forced to IMPLICIT display form, so that only the typmod coercion node will
745 * be visible when displaying the expression.
747 * NOTE: this does not need to work on domain types, because any typmod
748 * coercion for a domain is considered to be part of the type coercion
749 * needed to produce the domain value in the first place. So, no getBaseType.
755 bool hideInputCoercion)
760 /* Skip coercion if already done */
764 /* Suppress display of nested coercion steps */
765 if (hideInputCoercion)
769 * A negative typmod means that no actual coercion is needed, but we still
770 * want a RelabelType to ensure that the expression exposes the intended
773 if (targetTypMod < 0)
781 targetTypeId, targetTypMod,
782 ccontext, cformat, location);
787 * We don't need to perform any actual coercion step, but we should
788 * apply a RelabelType to ensure that the expression exposes the
793 cformat, location,
false);
800 * Mark a coercion node as IMPLICIT so it will never be displayed by
801 * ruleutils.c. We use this when we generate a nest of coercion nodes
802 * to implement what is logically one conversion; the inner nodes are
803 * forced to IMPLICIT_CAST format. This does not change their semantics,
804 * only display behavior.
806 * It is caller error to call this on something that doesn't have a
807 * CoercionForm field.
831 * build_coercion_expression()
832 * Construct an expression tree for applying a pg_cast entry.
834 * This is used for both type-coercion and length-coercion operations,
835 * since there is no difference in terms of the calling convention.
841 Oid targetTypeId,
int32 targetTypMod,
854 elog(
ERROR,
"cache lookup failed for function %u", funcId);
858 * These Asserts essentially check that function is a legal coercion
859 * function. We can't make the seemingly obvious tests on prorettype
860 * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
861 * various binary-compatibility cases.
863 /* Assert(targetTypeId == procstruct->prorettype); */
864 Assert(!procstruct->proretset);
865 Assert(procstruct->prokind == PROKIND_FUNCTION);
866 nargs = procstruct->pronargs;
867 Assert(nargs >= 1 && nargs <= 3);
868 /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
869 Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
870 Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
877 /* We build an ordinary FuncExpr with special arguments */
888 /* Pass target typmod as an int4 constant */
902 /* Pass it a boolean isExplicit parameter, too */
917 return (
Node *) fexpr;
921 /* We need to build an ArrayCoerceExpr */
924 Oid sourceBaseTypeId;
925 int32 sourceBaseTypeMod;
926 Oid targetElementType;
930 * Look through any domain over the source array type. Note we don't
931 * expect that the target type is a domain; it must be a plain array.
932 * (To get to a domain target type, we'll do coerce_to_domain later.)
939 * Set up a CaseTestExpr representing one element of the source array.
940 * This is an abuse of CaseTestExpr, but it's OK as long as there
941 * can't be any CaseExpr or ArrayCoerceExpr within the completed
946 ctest->typeMod = sourceBaseTypeMod;
947 ctest->collation =
InvalidOid;
/* Assume coercions don't care */
949 /* And coerce it to the target element type */
961 if (elemexpr == NULL)
/* shouldn't happen */
962 elog(
ERROR,
"failed to coerce array element type as expected");
969 * Label the output as having a particular element typmod only if we
970 * ended up with a per-element expression that is labeled that way.
973 /* resultcollid will be set by parse_collate.c */
974 acoerce->coerceformat = cformat;
977 return (
Node *) acoerce;
981 /* We need to build a CoerceViaIO node */
988 /* resultcollid will be set by parse_collate.c */
989 iocoerce->coerceformat = cformat;
992 return (
Node *) iocoerce;
996 elog(
ERROR,
"unsupported pathtype %d in build_coercion_expression",
998 return NULL;
/* keep compiler quiet */
1004 * coerce_record_to_complex
1005 * Coerce a RECORD to a specific composite type.
1007 * Currently we only support this for inputs that are RowExprs or whole-row
1019 int32 baseTypeMod = -1;
1030 * Since the RowExpr must be of type RECORD, we needn't worry about it
1031 * containing any dropped columns.
1035 else if (node &&
IsA(node,
Var) &&
1038 int rtindex = ((
Var *) node)->varno;
1039 int sublevels_up = ((
Var *) node)->varlevelsup;
1040 int vlocation = ((
Var *) node)->location;
1048 (
errcode(ERRCODE_CANNOT_COERCE),
1049 errmsg(
"cannot cast type %s to %s",
1055 * Look up the composite type, accounting for possibility that what we are
1056 * given is a domain over composite.
1061 /* Process the fields */
1065 for (
i = 0;
i < tupdesc->
natts;
i++)
1072 /* Fill in NULLs for dropped columns in rowtype */
1073 if (attr->attisdropped)
1076 * can't use atttypid here, but it doesn't really matter what type
1077 * the Const claims to be.
1086 (
errcode(ERRCODE_CANNOT_COERCE),
1087 errmsg(
"cannot cast type %s to %s",
1090 errdetail(
"Input has too few columns."),
1104 (
errcode(ERRCODE_CANNOT_COERCE),
1105 errmsg(
"cannot cast type %s to %s",
1108 errdetail(
"Cannot cast type %s to %s in column %d.",
1113 newargs =
lappend(newargs, cexpr);
1119 (
errcode(ERRCODE_CANNOT_COERCE),
1120 errmsg(
"cannot cast type %s to %s",
1123 errdetail(
"Input has too many columns."),
1129 rowexpr->
args = newargs;
1130 rowexpr->row_typeid = baseTypeId;
1131 rowexpr->row_format = cformat;
1132 rowexpr->colnames =
NIL;
/* not needed for named target type */
1135 /* If target is a domain, apply constraints */
1136 if (baseTypeId != targetTypeId)
1140 baseTypeId, baseTypeMod,
1142 ccontext, cformat, location,
1146 return (
Node *) rowexpr;
1150 * coerce_to_boolean()
1151 * Coerce an argument of a construct that requires boolean input
1152 * (AND, OR, NOT, etc). Also check that input is not a set.
1154 * Returns the possibly-transformed node tree.
1156 * As with coerce_type, pstate may be NULL if no special unknown-Param
1157 * processing is wanted.
1161 const char *constructName)
1165 if (inputTypeId != BOOLOID)
1174 if (newnode == NULL)
1176 (
errcode(ERRCODE_DATATYPE_MISMATCH),
1177 /* translator: first %s is name of a SQL construct, eg WHERE */
1178 errmsg(
"argument of %s must be type %s, not type %s",
1179 constructName,
"boolean",
1187 (
errcode(ERRCODE_DATATYPE_MISMATCH),
1188 /* translator: %s is name of a SQL construct, eg WHERE */
1189 errmsg(
"argument of %s must not return a set",
1197 * coerce_to_specific_type_typmod()
1198 * Coerce an argument of a construct that requires a specific data type,
1199 * with a specific typmod. Also check that input is not a set.
1201 * Returns the possibly-transformed node tree.
1203 * As with coerce_type, pstate may be NULL if no special unknown-Param
1204 * processing is wanted.
1208 Oid targetTypeId,
int32 targetTypmod,
1209 const char *constructName)
1213 if (inputTypeId != targetTypeId)
1218 targetTypeId, targetTypmod,
1222 if (newnode == NULL)
1224 (
errcode(ERRCODE_DATATYPE_MISMATCH),
1225 /* translator: first %s is name of a SQL construct, eg LIMIT */
1226 errmsg(
"argument of %s must be type %s, not type %s",
1236 (
errcode(ERRCODE_DATATYPE_MISMATCH),
1237 /* translator: %s is name of a SQL construct, eg LIMIT */
1238 errmsg(
"argument of %s must not return a set",
1246 * coerce_to_specific_type()
1247 * Coerce an argument of a construct that requires a specific data type.
1248 * Also check that input is not a set.
1250 * Returns the possibly-transformed node tree.
1252 * As with coerce_type, pstate may be NULL if no special unknown-Param
1253 * processing is wanted.
1258 const char *constructName)
1266 * coerce_null_to_domain()
1267 * Build a NULL constant, then wrap it in CoerceToDomain
1268 * if the desired type is a domain type. This allows any
1269 * NOT NULL domain constraint to be enforced at runtime.
1273 int typlen,
bool typbyval)
1277 int32 baseTypeMod = typmod;
1280 * The constant must appear to have the domain's base type/typmod, else
1281 * coerce_to_domain() will apply a length coercion which is useless.
1291 if (typid != baseTypeId)
1293 baseTypeId, baseTypeMod,
1303 * parser_coercion_errposition - report coercion error location, if possible
1305 * We prefer to point at the coercion request (CAST, ::, etc) if possible;
1306 * but there may be no such location in the case of an implicit coercion.
1307 * In that case point at the input expression.
1309 * XXX possibly this is more generally useful than coercion errors;
1310 * if so, should rename and place with parser_errposition.
1314 int coerce_location,
1317 if (coerce_location >= 0)
1325 * select_common_type()
1326 * Determine the common supertype of a list of input expressions.
1327 * This is used for determining the output type of CASE, UNION,
1328 * and similar constructs.
1330 * 'exprs' is a *nonempty* list of expressions. Note that earlier items
1331 * in the list will be preferred if there is doubt.
1332 * 'context' is a phrase to use in the error message if we fail to select
1333 * a usable type. Pass NULL to have the routine return InvalidOid
1334 * rather than throwing an error on failure.
1335 * 'which_expr': if not NULL, receives a pointer to the particular input
1336 * expression from which the result type was taken.
1338 * Caution: "failure" just means that there were inputs of different type
1339 * categories. It is not guaranteed that all the inputs are coercible to the
1340 * selected type; caller must check that (see verify_common_type).
1358 * If all input types are valid and exactly the same, just pick that type.
1359 * This is the only way that we will resolve the result as being a domain
1360 * type; otherwise domains are smashed to their base types for comparison.
1362 if (ptype != UNKNOWNOID)
1372 if (lc == NULL)
/* got to the end of the list? */
1375 *which_expr = pexpr;
1381 * Nope, so set up for the full algorithm. Note that at this point, lc
1382 * points to the first list item with type different from pexpr's; we need
1383 * not re-examine any items the previous loop advanced over.
1393 /* move on to next one if no new information... */
1394 if (ntype != UNKNOWNOID && ntype != ptype)
1400 if (ptype == UNKNOWNOID)
1402 /* so far, only unknowns so take anything... */
1405 pcategory = ncategory;
1406 pispreferred = nispreferred;
1408 else if (ncategory != pcategory)
1411 * both types in different categories? then not much hope...
1413 if (context == NULL)
1416 (
errcode(ERRCODE_DATATYPE_MISMATCH),
1418 translator: first %s is name of a SQL construct, eg CASE */
1419 errmsg(
"%s types %s and %s cannot be matched",
1425 else if (!pispreferred &&
1430 * take new type if can coerce to it implicitly but not the
1431 * other way; but if we have a preferred type, stay on it.
1435 pcategory = ncategory;
1436 pispreferred = nispreferred;
1442 * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1443 * then resolve as type TEXT. This situation comes up with constructs
1444 * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1445 * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1446 * output type as UNKNOWN, but that really doesn't work, because we'd
1447 * probably end up needing a runtime coercion from UNKNOWN to something
1448 * else, and we usually won't have it. We need to coerce the unknown
1449 * literals while they are still literals, so a decision has to be made
1452 if (ptype == UNKNOWNOID)
1456 *which_expr = pexpr;
1461 * select_common_type_from_oids()
1462 * Determine the common supertype of an array of type OIDs.
1464 * This is the same logic as select_common_type(), but working from
1465 * an array of type OIDs not a list of expressions. As in that function,
1466 * earlier entries in the array have some preference over later ones.
1467 * On failure, return InvalidOid if noerror is true, else throw an error.
1469 * Caution: "failure" just means that there were inputs of different type
1470 * categories. It is not guaranteed that all the inputs are coercible to the
1471 * selected type; caller must check that (see verify_common_type_from_oids).
1473 * Note: neither caller will pass any UNKNOWNOID entries, so the tests
1474 * for that in this function are dead code. However, they don't cost much,
1475 * and it seems better to keep this logic as close to select_common_type()
1489 /* If all input types are valid and exactly the same, pick that type. */
1490 if (ptype != UNKNOWNOID)
1492 for (;
i < nargs;
i++)
1494 if (typeids[
i] != ptype)
1502 * Nope, so set up for the full algorithm. Note that at this point, we
1503 * can skip array entries before "i"; they are all equal to ptype.
1508 for (;
i < nargs;
i++)
1512 /* move on to next one if no new information... */
1513 if (ntype != UNKNOWNOID && ntype != ptype)
1519 if (ptype == UNKNOWNOID)
1521 /* so far, only unknowns so take anything... */
1523 pcategory = ncategory;
1524 pispreferred = nispreferred;
1526 else if (ncategory != pcategory)
1529 * both types in different categories? then not much hope...
1534 (
errcode(ERRCODE_DATATYPE_MISMATCH),
1535 errmsg(
"argument types %s and %s cannot be matched",
1539 else if (!pispreferred &&
1544 * take new type if can coerce to it implicitly but not the
1545 * other way; but if we have a preferred type, stay on it.
1548 pcategory = ncategory;
1549 pispreferred = nispreferred;
1554 /* Like select_common_type(), choose TEXT if all inputs were UNKNOWN */
1555 if (ptype == UNKNOWNOID)
1562 * coerce_to_common_type()
1563 * Coerce an expression to the given type.
1565 * This is used following select_common_type() to coerce the individual
1566 * expressions to the desired type. 'context' is a phrase to use in the
1567 * error message if we fail to coerce.
1569 * As with coerce_type, pstate may be NULL if no special unknown-Param
1570 * processing is wanted.
1574 Oid targetTypeId,
const char *context)
1578 if (inputTypeId == targetTypeId)
1579 return node;
/* no work */
1581 node =
coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1585 (
errcode(ERRCODE_CANNOT_COERCE),
1586 /* translator: first %s is name of a SQL construct, eg CASE */
1587 errmsg(
"%s could not convert type %s to %s",
1596 * verify_common_type()
1597 * Verify that all input types can be coerced to a proposed common type.
1598 * Return true if so, false if not all coercions are possible.
1600 * Most callers of select_common_type() don't need to do this explicitly
1601 * because the checks will happen while trying to convert input expressions
1602 * to the right type, e.g. in coerce_to_common_type(). However, if a separate
1603 * check step is needed to validate the applicability of the common type, call
1623 * verify_common_type_from_oids()
1624 * As above, but work from an array of type OIDs.
1629 for (
int i = 0;
i < nargs;
i++)
1638 * select_common_typmod()
1639 * Determine the common typmod of a list of input expressions.
1641 * common_type is the selected common type of the expressions, typically
1642 * computed using select_common_type().
1655 /* Types must match */
1665 /* As soon as we see a non-matching typmod, fall back to -1 */
1675 * check_generic_type_consistency()
1676 * Are the actual arguments potentially compatible with a
1677 * polymorphic function?
1679 * The argument consistency rules are:
1681 * 1) All arguments declared ANYELEMENT must have the same datatype.
1682 * 2) All arguments declared ANYARRAY must have the same datatype,
1683 * which must be a varlena array type.
1684 * 3) All arguments declared ANYRANGE must be the same range type.
1685 * Similarly, all arguments declared ANYMULTIRANGE must be the same
1686 * multirange type; and if both of these appear, the ANYRANGE type
1687 * must be the element type of the ANYMULTIRANGE type.
1688 * 4) If there are arguments of more than one of these polymorphic types,
1689 * the array element type and/or range subtype must be the same as each
1690 * other and the same as the ANYELEMENT type.
1691 * 5) ANYENUM is treated the same as ANYELEMENT except that if it is used
1692 * (alone or in combination with plain ANYELEMENT), we add the extra
1693 * condition that the ANYELEMENT type must be an enum.
1694 * 6) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1695 * we add the extra condition that the ANYELEMENT type must not be an array.
1696 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1697 * is an extra restriction if not.)
1698 * 7) All arguments declared ANYCOMPATIBLE must be implicitly castable
1699 * to a common supertype (chosen as per select_common_type's rules).
1700 * ANYCOMPATIBLENONARRAY works like ANYCOMPATIBLE but also requires the
1701 * common supertype to not be an array. If there are ANYCOMPATIBLEARRAY
1702 * or ANYCOMPATIBLERANGE or ANYCOMPATIBLEMULTIRANGE arguments, their element
1703 * types or subtypes are included while making the choice of common supertype.
1704 * 8) The resolved type of ANYCOMPATIBLEARRAY arguments will be the array
1705 * type over the common supertype (which might not be the same array type
1706 * as any of the original arrays).
1707 * 9) All ANYCOMPATIBLERANGE arguments must be the exact same range type
1708 * (after domain flattening), since we have no preference rule that would
1709 * let us choose one over another. Furthermore, that range's subtype
1710 * must exactly match the common supertype chosen by rule 7.
1711 * 10) All ANYCOMPATIBLEMULTIRANGE arguments must be the exact same multirange
1712 * type (after domain flattening), since we have no preference rule that
1713 * would let us choose one over another. Furthermore, if ANYCOMPATIBLERANGE
1714 * also appears, that range type must be the multirange's element type;
1715 * otherwise, the multirange's range's subtype must exactly match the
1716 * common supertype chosen by rule 7.
1718 * Domains over arrays match ANYARRAY, and are immediately flattened to their
1719 * base type. (Thus, for example, we will consider it a match if one ANYARRAY
1720 * argument is a domain over int4[] while another one is just int4[].) Also
1721 * notice that such a domain does *not* match ANYNONARRAY. The same goes
1722 * for ANYCOMPATIBLEARRAY and ANYCOMPATIBLENONARRAY.
1724 * Similarly, domains over ranges match ANYRANGE or ANYCOMPATIBLERANGE,
1725 * and are immediately flattened to their base type. Likewise, domains
1726 * over multiranges match ANYMULTIRANGE or ANYCOMPATIBLEMULTIRANGE and are
1727 * immediately flattened to their base type.
1729 * Note that domains aren't currently considered to match ANYENUM,
1730 * even if their base type would match.
1732 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1733 * argument, assume it is okay.
1735 * We do not ereport here, but just return false if a rule is violated.
1739 const Oid *declared_arg_types,
1751 bool have_anynonarray =
false;
1752 bool have_anyenum =
false;
1753 bool have_anycompatible_nonarray =
false;
1754 int n_anycompatible_args = 0;
1758 * Loop through the arguments to see if we have any that are polymorphic.
1759 * If so, require the actual types to be consistent.
1762 for (
int j = 0;
j < nargs;
j++)
1764 Oid decl_type = declared_arg_types[
j];
1765 Oid actual_type = actual_arg_types[
j];
1767 if (decl_type == ANYELEMENTOID ||
1768 decl_type == ANYNONARRAYOID ||
1769 decl_type == ANYENUMOID)
1771 if (decl_type == ANYNONARRAYOID)
1772 have_anynonarray =
true;
1773 else if (decl_type == ANYENUMOID)
1774 have_anyenum =
true;
1775 if (actual_type == UNKNOWNOID)
1777 if (
OidIsValid(elem_typeid) && actual_type != elem_typeid)
1779 elem_typeid = actual_type;
1781 else if (decl_type == ANYARRAYOID)
1783 if (actual_type == UNKNOWNOID)
1785 actual_type =
getBaseType(actual_type);
/* flatten domains */
1786 if (
OidIsValid(array_typeid) && actual_type != array_typeid)
1788 array_typeid = actual_type;
1790 else if (decl_type == ANYRANGEOID)
1792 if (actual_type == UNKNOWNOID)
1794 actual_type =
getBaseType(actual_type);
/* flatten domains */
1795 if (
OidIsValid(range_typeid) && actual_type != range_typeid)
1797 range_typeid = actual_type;
1799 else if (decl_type == ANYMULTIRANGEOID)
1801 if (actual_type == UNKNOWNOID)
1803 actual_type =
getBaseType(actual_type);
/* flatten domains */
1804 if (
OidIsValid(multirange_typeid) && actual_type != multirange_typeid)
1806 multirange_typeid = actual_type;
1808 else if (decl_type == ANYCOMPATIBLEOID ||
1809 decl_type == ANYCOMPATIBLENONARRAYOID)
1811 if (decl_type == ANYCOMPATIBLENONARRAYOID)
1812 have_anycompatible_nonarray =
true;
1813 if (actual_type == UNKNOWNOID)
1815 /* collect the actual types of non-unknown COMPATIBLE args */
1816 anycompatible_actual_types[n_anycompatible_args++] = actual_type;
1818 else if (decl_type == ANYCOMPATIBLEARRAYOID)
1822 if (actual_type == UNKNOWNOID)
1824 actual_type =
getBaseType(actual_type);
/* flatten domains */
1827 return false;
/* not an array */
1828 /* collect the element type for common-supertype choice */
1829 anycompatible_actual_types[n_anycompatible_args++] = elem_type;
1831 else if (decl_type == ANYCOMPATIBLERANGEOID)
1833 if (actual_type == UNKNOWNOID)
1835 actual_type =
getBaseType(actual_type);
/* flatten domains */
1838 /* All ANYCOMPATIBLERANGE arguments must be the same type */
1839 if (anycompatible_range_typeid != actual_type)
1844 anycompatible_range_typeid = actual_type;
1846 if (!
OidIsValid(anycompatible_range_typelem))
1847 return false;
/* not a range type */
1848 /* collect the subtype for common-supertype choice */
1849 anycompatible_actual_types[n_anycompatible_args++] = anycompatible_range_typelem;
1852 else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
1854 if (actual_type == UNKNOWNOID)
1856 actual_type =
getBaseType(actual_type);
/* flatten domains */
1857 if (
OidIsValid(anycompatible_multirange_typeid))
1859 /* All ANYCOMPATIBLEMULTIRANGE arguments must be the same type */
1860 if (anycompatible_multirange_typeid != actual_type)
1865 anycompatible_multirange_typeid = actual_type;
1867 if (!
OidIsValid(anycompatible_multirange_typelem))
1868 return false;
/* not a multirange type */
1869 /* we'll consider the subtype below */
1874 /* Get the element type based on the array type, if we have one */
1877 if (array_typeid == ANYARRAYOID)
1880 * Special case for matching ANYARRAY input to an ANYARRAY
1881 * argument: allow it for now. enforce_generic_type_consistency()
1882 * might complain later, depending on the presence of other
1883 * polymorphic arguments or results, but it will deliver a less
1884 * surprising error message than "function does not exist".
1886 * (If you think to change this, note that can_coerce_type will
1887 * consider such a situation as a match, so that we might not even
1897 return false;
/* should be an array, but isn't */
1902 * if we don't have an element type yet, use the one we just
1905 elem_typeid = array_typelem;
1907 else if (array_typelem != elem_typeid)
1909 /* otherwise, they better match */
1915 /* Deduce range type from multirange type, or check that they agree */
1918 Oid multirange_typelem;
1922 return false;
/* should be a multirange, but isn't */
1926 /* If we don't have a range type yet, use the one we just got */
1927 range_typeid = multirange_typelem;
1930 return false;
/* should be a range, but isn't */
1932 else if (multirange_typelem != range_typeid)
1934 /* otherwise, they better match */
1939 /* Get the element type based on the range type, if we have one */
1944 return false;
/* should be a range, but isn't */
1949 * If we don't have an element type yet, use the one we just got
1951 elem_typeid = range_typelem;
1953 else if (range_typelem != elem_typeid)
1955 /* otherwise, they better match */
1960 if (have_anynonarray)
1962 /* require the element type to not be an array or domain over array */
1969 /* require the element type to be an enum */
1974 /* Deduce range type from multirange type, or check that they agree */
1975 if (
OidIsValid(anycompatible_multirange_typeid))
1979 if (anycompatible_multirange_typelem !=
1980 anycompatible_range_typeid)
1985 anycompatible_range_typeid = anycompatible_multirange_typelem;
1987 if (!
OidIsValid(anycompatible_range_typelem))
1988 return false;
/* not a range type */
1989 /* collect the subtype for common-supertype choice */
1990 anycompatible_actual_types[n_anycompatible_args++] =
1991 anycompatible_range_typelem;
1995 /* Check matching of ANYCOMPATIBLE-family arguments, if any */
1996 if (n_anycompatible_args > 0)
1998 Oid anycompatible_typeid;
2000 anycompatible_typeid =
2002 anycompatible_actual_types,
2006 return false;
/* there's definitely no common supertype */
2008 /* We have to verify that the selected type actually works */
2010 n_anycompatible_args,
2011 anycompatible_actual_types))
2014 if (have_anycompatible_nonarray)
2017 * require the anycompatible type to not be an array or domain
2025 * The anycompatible type must exactly match the range element type,
2026 * if we were able to identify one. This checks compatibility for
2027 * anycompatiblemultirange too since that also sets
2028 * anycompatible_range_typelem above.
2030 if (
OidIsValid(anycompatible_range_typelem) &&
2031 anycompatible_range_typelem != anycompatible_typeid)
2040 * enforce_generic_type_consistency()
2041 * Make sure a polymorphic function is legally callable, and
2042 * deduce actual argument and result types.
2044 * If any polymorphic pseudotype is used in a function's arguments or
2045 * return type, we make sure the actual data types are consistent with
2046 * each other. The argument consistency rules are shown above for
2047 * check_generic_type_consistency().
2049 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
2050 * argument, we attempt to deduce the actual type it should have. If
2051 * successful, we alter that position of declared_arg_types[] so that
2052 * make_fn_arguments will coerce the literal to the right thing.
2054 * If we have polymorphic arguments of the ANYCOMPATIBLE family,
2055 * we similarly alter declared_arg_types[] entries to show the resolved
2056 * common supertype, so that make_fn_arguments will coerce the actual
2057 * arguments to the proper type.
2059 * Rules are applied to the function's return type (possibly altering it)
2060 * if it is declared as a polymorphic type and there is at least one
2061 * polymorphic argument type:
2063 * 1) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
2064 * argument's actual type as the function's return type.
2065 * 2) If return type is ANYARRAY, and any argument is ANYARRAY, use the
2066 * argument's actual type as the function's return type.
2067 * 3) Similarly, if return type is ANYRANGE or ANYMULTIRANGE, and any
2068 * argument is ANYRANGE or ANYMULTIRANGE, use that argument's actual type
2069 * (or the corresponding range or multirange type) as the function's return
2071 * 4) Otherwise, if return type is ANYELEMENT or ANYARRAY, and there is
2072 * at least one ANYELEMENT, ANYARRAY, ANYRANGE, or ANYMULTIRANGE input,
2073 * deduce the return type from those inputs, or throw error if we can't.
2074 * 5) Otherwise, if return type is ANYRANGE or ANYMULTIRANGE, throw error.
2075 * (We have no way to select a specific range type if the arguments don't
2076 * include ANYRANGE or ANYMULTIRANGE.)
2077 * 6) ANYENUM is treated the same as ANYELEMENT except that if it is used
2078 * (alone or in combination with plain ANYELEMENT), we add the extra
2079 * condition that the ANYELEMENT type must be an enum.
2080 * 7) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
2081 * we add the extra condition that the ANYELEMENT type must not be an array.
2082 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
2083 * is an extra restriction if not.)
2084 * 8) ANYCOMPATIBLE, ANYCOMPATIBLEARRAY, and ANYCOMPATIBLENONARRAY are handled
2085 * by resolving the common supertype of those arguments (or their element
2086 * types, for array inputs), and then coercing all those arguments to the
2087 * common supertype, or the array type over the common supertype for
2088 * ANYCOMPATIBLEARRAY.
2089 * 9) For ANYCOMPATIBLERANGE and ANYCOMPATIBLEMULTIRANGE, there must be at
2090 * least one non-UNKNOWN input matching those arguments, and all such
2091 * inputs must be the same range type (or its multirange type, as
2092 * appropriate), since we cannot deduce a range type from non-range types.
2093 * Furthermore, the range type's subtype is included while choosing the
2094 * common supertype for ANYCOMPATIBLE et al, and it must exactly match
2095 * that common supertype.
2097 * Domains over arrays or ranges match ANYARRAY or ANYRANGE arguments,
2098 * respectively, and are immediately flattened to their base type. (In
2099 * particular, if the return type is also ANYARRAY or ANYRANGE, we'll set
2100 * it to the base type not the domain type.) The same is true for
2101 * ANYMULTIRANGE, ANYCOMPATIBLEARRAY, ANYCOMPATIBLERANGE, and
2102 * ANYCOMPATIBLEMULTIRANGE.
2104 * When allow_poly is false, we are not expecting any of the actual_arg_types
2105 * to be polymorphic, and we should not return a polymorphic result type
2106 * either. When allow_poly is true, it is okay to have polymorphic "actual"
2107 * arg types, and we can return a matching polymorphic type as the result.
2108 * (This case is currently used only to check compatibility of an aggregate's
2109 * declaration with the underlying transfn.)
2111 * A special case is that we could see ANYARRAY as an actual_arg_type even
2112 * when allow_poly is false (this is possible only because pg_statistic has
2113 * columns shown as anyarray in the catalogs). We allow this to match a
2114 * declared ANYARRAY argument, but only if there is no other polymorphic
2115 * argument that we would need to match it with, and no need to determine
2116 * the element type to infer the result type. Note this means that functions
2117 * taking ANYARRAY had better behave sanely if applied to the pg_statistic
2118 * columns; they can't just assume that successive inputs are of the same
2119 * actual element type. There is no similar logic for ANYCOMPATIBLEARRAY;
2120 * there isn't a need for it since there are no catalog columns of that type,
2121 * so we won't see it as input. We could consider matching an actual ANYARRAY
2122 * input to an ANYCOMPATIBLEARRAY argument, but at present that seems useless
2123 * as well, since there's no value in using ANYCOMPATIBLEARRAY unless there's
2124 * at least one other ANYCOMPATIBLE-family argument or result.
2126 * Also, if there are no arguments declared to be of polymorphic types,
2127 * we'll return the rettype unmodified even if it's polymorphic. This should
2128 * never occur for user-declared functions, because CREATE FUNCTION prevents
2129 * it. But it does happen for some built-in functions, such as array_in().
2133 Oid *declared_arg_types,
2138 bool have_poly_anycompatible =
false;
2139 bool have_poly_unknowns =
false;
2150 bool have_anynonarray = (rettype == ANYNONARRAYOID);
2151 bool have_anyenum = (rettype == ANYENUMOID);
2152 bool have_anymultirange = (rettype == ANYMULTIRANGEOID);
2153 bool have_anycompatible_nonarray = (rettype == ANYCOMPATIBLENONARRAYOID);
2154 bool have_anycompatible_array = (rettype == ANYCOMPATIBLEARRAYOID);
2155 bool have_anycompatible_range = (rettype == ANYCOMPATIBLERANGEOID);
2156 bool have_anycompatible_multirange = (rettype == ANYCOMPATIBLEMULTIRANGEOID);
2157 int n_poly_args = 0;
/* this counts all family-1 arguments */
2158 int n_anycompatible_args = 0;
/* this counts only non-unknowns */
2162 * Loop through the arguments to see if we have any that are polymorphic.
2163 * If so, require the actual types to be consistent.
2166 for (
int j = 0;
j < nargs;
j++)
2168 Oid decl_type = declared_arg_types[
j];
2169 Oid actual_type = actual_arg_types[
j];
2171 if (decl_type == ANYELEMENTOID ||
2172 decl_type == ANYNONARRAYOID ||
2173 decl_type == ANYENUMOID)
2176 if (decl_type == ANYNONARRAYOID)
2177 have_anynonarray =
true;
2178 else if (decl_type == ANYENUMOID)
2179 have_anyenum =
true;
2180 if (actual_type == UNKNOWNOID)
2182 have_poly_unknowns =
true;
2185 if (allow_poly && decl_type == actual_type)
2186 continue;
/* no new information here */
2187 if (
OidIsValid(elem_typeid) && actual_type != elem_typeid)
2189 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2190 errmsg(
"arguments declared \"%s\" are not all alike",
"anyelement"),
2194 elem_typeid = actual_type;
2196 else if (decl_type == ANYARRAYOID)
2199 if (actual_type == UNKNOWNOID)
2201 have_poly_unknowns =
true;
2204 if (allow_poly && decl_type == actual_type)
2205 continue;
/* no new information here */
2206 actual_type =
getBaseType(actual_type);
/* flatten domains */
2207 if (
OidIsValid(array_typeid) && actual_type != array_typeid)
2209 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2210 errmsg(
"arguments declared \"%s\" are not all alike",
"anyarray"),
2214 array_typeid = actual_type;
2216 else if (decl_type == ANYRANGEOID)
2219 if (actual_type == UNKNOWNOID)
2221 have_poly_unknowns =
true;
2224 if (allow_poly && decl_type == actual_type)
2225 continue;
/* no new information here */
2226 actual_type =
getBaseType(actual_type);
/* flatten domains */
2227 if (
OidIsValid(range_typeid) && actual_type != range_typeid)
2229 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2230 errmsg(
"arguments declared \"%s\" are not all alike",
"anyrange"),
2234 range_typeid = actual_type;
2236 else if (decl_type == ANYMULTIRANGEOID)
2239 have_anymultirange =
true;
2240 if (actual_type == UNKNOWNOID)
2242 have_poly_unknowns =
true;
2245 if (allow_poly && decl_type == actual_type)
2246 continue;
/* no new information here */
2247 actual_type =
getBaseType(actual_type);
/* flatten domains */
2248 if (
OidIsValid(multirange_typeid) && actual_type != multirange_typeid)
2250 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2251 errmsg(
"arguments declared \"%s\" are not all alike",
"anymultirange"),
2255 multirange_typeid = actual_type;
2257 else if (decl_type == ANYCOMPATIBLEOID ||
2258 decl_type == ANYCOMPATIBLENONARRAYOID)
2260 have_poly_anycompatible =
true;
2261 if (decl_type == ANYCOMPATIBLENONARRAYOID)
2262 have_anycompatible_nonarray =
true;
2263 if (actual_type == UNKNOWNOID)
2265 if (allow_poly && decl_type == actual_type)
2266 continue;
/* no new information here */
2267 /* collect the actual types of non-unknown COMPATIBLE args */
2268 anycompatible_actual_types[n_anycompatible_args++] = actual_type;
2270 else if (decl_type == ANYCOMPATIBLEARRAYOID)
2272 Oid anycompatible_elem_type;
2274 have_poly_anycompatible =
true;
2275 have_anycompatible_array =
true;
2276 if (actual_type == UNKNOWNOID)
2278 if (allow_poly && decl_type == actual_type)
2279 continue;
/* no new information here */
2280 actual_type =
getBaseType(actual_type);
/* flatten domains */
2284 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2285 errmsg(
"argument declared %s is not an array but type %s",
2286 "anycompatiblearray",
2288 /* collect the element type for common-supertype choice */
2289 anycompatible_actual_types[n_anycompatible_args++] = anycompatible_elem_type;
2291 else if (decl_type == ANYCOMPATIBLERANGEOID)
2293 have_poly_anycompatible =
true;
2294 have_anycompatible_range =
true;
2295 if (actual_type == UNKNOWNOID)
2297 if (allow_poly && decl_type == actual_type)
2298 continue;
/* no new information here */
2299 actual_type =
getBaseType(actual_type);
/* flatten domains */
2302 /* All ANYCOMPATIBLERANGE arguments must be the same type */
2303 if (anycompatible_range_typeid != actual_type)
2305 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2306 errmsg(
"arguments declared \"%s\" are not all alike",
"anycompatiblerange"),
2313 anycompatible_range_typeid = actual_type;
2315 if (!
OidIsValid(anycompatible_range_typelem))
2317 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2318 errmsg(
"argument declared %s is not a range type but type %s",
2319 "anycompatiblerange",
2321 /* collect the subtype for common-supertype choice */
2322 anycompatible_actual_types[n_anycompatible_args++] = anycompatible_range_typelem;
2325 else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
2327 have_poly_anycompatible =
true;
2328 have_anycompatible_multirange =
true;
2329 if (actual_type == UNKNOWNOID)
2331 if (allow_poly && decl_type == actual_type)
2332 continue;
/* no new information here */
2333 actual_type =
getBaseType(actual_type);
/* flatten domains */
2334 if (
OidIsValid(anycompatible_multirange_typeid))
2336 /* All ANYCOMPATIBLEMULTIRANGE arguments must be the same type */
2337 if (anycompatible_multirange_typeid != actual_type)
2339 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2340 errmsg(
"arguments declared \"%s\" are not all alike",
"anycompatiblemultirange"),
2347 anycompatible_multirange_typeid = actual_type;
2349 if (!
OidIsValid(anycompatible_multirange_typelem))
2351 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2352 errmsg(
"argument declared %s is not a multirange type but type %s",
2353 "anycompatiblemultirange",
2355 /* we'll consider the subtype below */
2361 * Fast Track: if none of the arguments are polymorphic, return the
2362 * unmodified rettype. Not our job to resolve it if it's polymorphic.
2364 if (n_poly_args == 0 && !have_poly_anycompatible)
2367 /* Check matching of family-1 polymorphic arguments, if any */
2370 /* Get the element type based on the array type, if we have one */
2375 if (array_typeid == ANYARRAYOID)
2378 * Special case for matching ANYARRAY input to an ANYARRAY
2379 * argument: allow it iff no other arguments are family-1
2380 * polymorphics (otherwise we couldn't be sure whether the
2381 * array element type matches up) and the result type doesn't
2382 * require us to infer a specific element type.
2384 if (n_poly_args != 1 ||
2385 (rettype != ANYARRAYOID &&
2386 IsPolymorphicTypeFamily1(rettype)))
2388 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2389 errmsg(
"cannot determine element type of \"anyarray\" argument")));
2390 array_typelem = ANYELEMENTOID;
2397 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2398 errmsg(
"argument declared %s is not an array but type %s",
2405 * if we don't have an element type yet, use the one we just
2408 elem_typeid = array_typelem;
2410 else if (array_typelem != elem_typeid)
2412 /* otherwise, they better match */
2414 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2415 errmsg(
"argument declared %s is not consistent with argument declared %s",
2416 "anyarray",
"anyelement"),
2423 /* Deduce range type from multirange type, or vice versa */
2426 Oid multirange_typelem;
2431 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2432 errmsg(
"argument declared %s is not a multirange type but type %s",
2438 /* if we don't have a range type yet, use the one we just got */
2439 range_typeid = multirange_typelem;
2441 else if (multirange_typelem != range_typeid)
2443 /* otherwise, they better match */
2445 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2446 errmsg(
"argument declared %s is not consistent with argument declared %s",
2447 "anymultirange",
"anyrange"),
2453 else if (have_anymultirange &&
OidIsValid(range_typeid))
2456 /* We'll complain below if that didn't work */
2459 /* Get the element type based on the range type, if we have one */
2467 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2468 errmsg(
"argument declared %s is not a range type but type %s",
2475 * if we don't have an element type yet, use the one we just
2478 elem_typeid = range_typelem;
2480 else if (range_typelem != elem_typeid)
2482 /* otherwise, they better match */
2484 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2485 errmsg(
"argument declared %s is not consistent with argument declared %s",
2486 "anyrange",
"anyelement"),
2497 elem_typeid = ANYELEMENTOID;
2498 array_typeid = ANYARRAYOID;
2499 range_typeid = ANYRANGEOID;
2500 multirange_typeid = ANYMULTIRANGEOID;
2505 * Only way to get here is if all the family-1 polymorphic
2506 * arguments have UNKNOWN inputs.
2509 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2510 errmsg(
"could not determine polymorphic type because input has type %s",
2515 if (have_anynonarray && elem_typeid != ANYELEMENTOID)
2518 * require the element type to not be an array or domain over
2523 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2524 errmsg(
"type matched to anynonarray is an array type: %s",
2528 if (have_anyenum && elem_typeid != ANYELEMENTOID)
2530 /* require the element type to be an enum */
2533 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2534 errmsg(
"type matched to anyenum is not an enum type: %s",
2539 /* Check matching of family-2 polymorphic arguments, if any */
2540 if (have_poly_anycompatible)
2542 /* Deduce range type from multirange type, or vice versa */
2543 if (
OidIsValid(anycompatible_multirange_typeid))
2547 if (anycompatible_multirange_typelem !=
2548 anycompatible_range_typeid)
2550 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2551 errmsg(
"argument declared %s is not consistent with argument declared %s",
2552 "anycompatiblemultirange",
2553 "anycompatiblerange"),
2560 anycompatible_range_typeid = anycompatible_multirange_typelem;
2562 if (!
OidIsValid(anycompatible_range_typelem))
2564 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2565 errmsg(
"argument declared %s is not a multirange type but type %s",
2566 "anycompatiblemultirange",
2568 /* this enables element type matching check below */
2569 have_anycompatible_range =
true;
2570 /* collect the subtype for common-supertype choice */
2571 anycompatible_actual_types[n_anycompatible_args++] =
2572 anycompatible_range_typelem;
2575 else if (have_anycompatible_multirange &&
2579 /* We'll complain below if that didn't work */
2582 if (n_anycompatible_args > 0)
2584 anycompatible_typeid =
2586 anycompatible_actual_types,
2589 /* We have to verify that the selected type actually works */
2591 n_anycompatible_args,
2592 anycompatible_actual_types))
2594 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2595 errmsg(
"arguments of anycompatible family cannot be cast to a common type")));
2597 if (have_anycompatible_array)
2599 anycompatible_array_typeid =
get_array_type(anycompatible_typeid);
2602 (
errcode(ERRCODE_UNDEFINED_OBJECT),
2603 errmsg(
"could not find array type for data type %s",
2607 if (have_anycompatible_range)
2609 /* we can't infer a range type from the others */
2612 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2613 errmsg(
"could not determine polymorphic type %s because input has type %s",
2614 "anycompatiblerange",
"unknown")));
2617 * the anycompatible type must exactly match the range element
2620 if (anycompatible_range_typelem != anycompatible_typeid)
2622 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2623 errmsg(
"anycompatiblerange type %s does not match anycompatible type %s",
2628 if (have_anycompatible_multirange)
2630 /* we can't infer a multirange type from the others */
2631 if (!
OidIsValid(anycompatible_multirange_typeid))
2633 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2634 errmsg(
"could not determine polymorphic type %s because input has type %s",
2635 "anycompatiblemultirange",
"unknown")));
2638 * the anycompatible type must exactly match the multirange
2641 if (anycompatible_range_typelem != anycompatible_typeid)
2643 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2644 errmsg(
"anycompatiblemultirange type %s does not match anycompatible type %s",
2649 if (have_anycompatible_nonarray)
2652 * require the element type to not be an array or domain over
2657 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2658 errmsg(
"type matched to anycompatiblenonarray is an array type: %s",
2666 anycompatible_typeid = ANYCOMPATIBLEOID;
2667 anycompatible_array_typeid = ANYCOMPATIBLEARRAYOID;
2668 anycompatible_range_typeid = ANYCOMPATIBLERANGEOID;
2669 anycompatible_multirange_typeid = ANYCOMPATIBLEMULTIRANGEOID;
2674 * Only way to get here is if all the family-2 polymorphic
2675 * arguments have UNKNOWN inputs. Resolve to TEXT as
2676 * select_common_type() would do. That doesn't license us to
2677 * use TEXTRANGE or TEXTMULTIRANGE, though.
2679 anycompatible_typeid = TEXTOID;
2680 anycompatible_array_typeid = TEXTARRAYOID;
2681 if (have_anycompatible_range)
2683 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2684 errmsg(
"could not determine polymorphic type %s because input has type %s",
2685 "anycompatiblerange",
"unknown")));
2686 if (have_anycompatible_multirange)
2688 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2689 errmsg(
"could not determine polymorphic type %s because input has type %s",
2690 "anycompatiblemultirange",
"unknown")));
2694 /* replace family-2 polymorphic types by selected types */
2695 for (
int j = 0;
j < nargs;
j++)
2697 Oid decl_type = declared_arg_types[
j];
2699 if (decl_type == ANYCOMPATIBLEOID ||
2700 decl_type == ANYCOMPATIBLENONARRAYOID)
2701 declared_arg_types[
j] = anycompatible_typeid;
2702 else if (decl_type == ANYCOMPATIBLEARRAYOID)
2703 declared_arg_types[
j] = anycompatible_array_typeid;
2704 else if (decl_type == ANYCOMPATIBLERANGEOID)
2705 declared_arg_types[
j] = anycompatible_range_typeid;
2706 else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
2707 declared_arg_types[
j] = anycompatible_multirange_typeid;
2712 * If we had any UNKNOWN inputs for family-1 polymorphic arguments,
2713 * re-scan to assign correct types to them.
2715 * Note: we don't have to consider unknown inputs that were matched to
2716 * family-2 polymorphic arguments, because we forcibly updated their
2717 * declared_arg_types[] positions just above.
2719 if (have_poly_unknowns)
2721 for (
int j = 0;
j < nargs;
j++)
2723 Oid decl_type = declared_arg_types[
j];
2724 Oid actual_type = actual_arg_types[
j];
2726 if (actual_type != UNKNOWNOID)
2729 if (decl_type == ANYELEMENTOID ||
2730 decl_type == ANYNONARRAYOID ||
2731 decl_type == ANYENUMOID)
2732 declared_arg_types[
j] = elem_typeid;
2733 else if (decl_type == ANYARRAYOID)
2740 (
errcode(ERRCODE_UNDEFINED_OBJECT),
2741 errmsg(
"could not find array type for data type %s",
2744 declared_arg_types[
j] = array_typeid;
2746 else if (decl_type == ANYRANGEOID)
2750 /* we can't infer a range type from the others */
2752 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2753 errmsg(
"could not determine polymorphic type %s because input has type %s",
2754 "anyrange",
"unknown")));
2756 declared_arg_types[
j] = range_typeid;
2758 else if (decl_type == ANYMULTIRANGEOID)
2762 /* we can't infer a multirange type from the others */
2764 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2765 errmsg(
"could not determine polymorphic type %s because input has type %s",
2766 "anymultirange",
"unknown")));
2768 declared_arg_types[
j] = multirange_typeid;
2773 /* if we return ANYELEMENT use the appropriate argument type */
2774 if (rettype == ANYELEMENTOID ||
2775 rettype == ANYNONARRAYOID ||
2776 rettype == ANYENUMOID)
2779 /* if we return ANYARRAY use the appropriate argument type */
2780 if (rettype == ANYARRAYOID)
2787 (
errcode(ERRCODE_UNDEFINED_OBJECT),
2788 errmsg(
"could not find array type for data type %s",
2791 return array_typeid;
2794 /* if we return ANYRANGE use the appropriate argument type */
2795 if (rettype == ANYRANGEOID)
2797 /* this error is unreachable if the function signature is valid: */
2800 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2801 errmsg_internal(
"could not determine polymorphic type %s because input has type %s",
2802 "anyrange",
"unknown")));
2803 return range_typeid;
2806 /* if we return ANYMULTIRANGE use the appropriate argument type */
2807 if (rettype == ANYMULTIRANGEOID)
2809 /* this error is unreachable if the function signature is valid: */
2812 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2813 errmsg_internal(
"could not determine polymorphic type %s because input has type %s",
2814 "anymultirange",
"unknown")));
2815 return multirange_typeid;
2818 /* if we return ANYCOMPATIBLE use the appropriate type */
2819 if (rettype == ANYCOMPATIBLEOID ||
2820 rettype == ANYCOMPATIBLENONARRAYOID)
2822 /* this error is unreachable if the function signature is valid: */
2825 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2827 return anycompatible_typeid;
2830 /* if we return ANYCOMPATIBLEARRAY use the appropriate type */
2831 if (rettype == ANYCOMPATIBLEARRAYOID)
2833 /* this error is unreachable if the function signature is valid: */
2836 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2838 return anycompatible_array_typeid;
2841 /* if we return ANYCOMPATIBLERANGE use the appropriate argument type */
2842 if (rettype == ANYCOMPATIBLERANGEOID)
2844 /* this error is unreachable if the function signature is valid: */
2847 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2849 return anycompatible_range_typeid;
2852 /* if we return ANYCOMPATIBLEMULTIRANGE use the appropriate argument type */
2853 if (rettype == ANYCOMPATIBLEMULTIRANGEOID)
2855 /* this error is unreachable if the function signature is valid: */
2856 if (!
OidIsValid(anycompatible_multirange_typeid))
2858 (
errcode(ERRCODE_DATATYPE_MISMATCH),
2860 return anycompatible_multirange_typeid;
2863 /* we don't return a generic type; send back the original return type */
2868 * check_valid_polymorphic_signature()
2869 * Is a proposed function signature valid per polymorphism rules?
2871 * Returns NULL if the signature is valid (either ret_type is not polymorphic,
2872 * or it can be deduced from the given declared argument types). Otherwise,
2873 * returns a palloc'd, already translated errdetail string saying why not.
2877 const Oid *declared_arg_types,
2880 if (ret_type == ANYRANGEOID || ret_type == ANYMULTIRANGEOID)
2883 * ANYRANGE and ANYMULTIRANGE require an ANYRANGE or ANYMULTIRANGE
2884 * input, else we can't tell which of several range types with the
2885 * same element type to use.
2887 for (
int i = 0;
i < nargs;
i++)
2889 if (declared_arg_types[
i] == ANYRANGEOID ||
2890 declared_arg_types[
i] == ANYMULTIRANGEOID)
2891 return NULL;
/* OK */
2893 return psprintf(
_(
"A result of type %s requires at least one input of type anyrange or anymultirange."),
2896 else if (ret_type == ANYCOMPATIBLERANGEOID || ret_type == ANYCOMPATIBLEMULTIRANGEOID)
2899 * ANYCOMPATIBLERANGE and ANYCOMPATIBLEMULTIRANGE require an
2900 * ANYCOMPATIBLERANGE or ANYCOMPATIBLEMULTIRANGE input, else we can't
2901 * tell which of several range types with the same element type to
2904 for (
int i = 0;
i < nargs;
i++)
2906 if (declared_arg_types[
i] == ANYCOMPATIBLERANGEOID ||
2907 declared_arg_types[
i] == ANYCOMPATIBLEMULTIRANGEOID)
2908 return NULL;
/* OK */
2910 return psprintf(
_(
"A result of type %s requires at least one input of type anycompatiblerange or anycompatiblemultirange."),
2913 else if (IsPolymorphicTypeFamily1(ret_type))
2915 /* Otherwise, any family-1 type can be deduced from any other */
2916 for (
int i = 0;
i < nargs;
i++)
2918 if (IsPolymorphicTypeFamily1(declared_arg_types[
i]))
2919 return NULL;
/* OK */
2921 /* Keep this list in sync with IsPolymorphicTypeFamily1! */
2922 return psprintf(
_(
"A result of type %s requires at least one input of type anyelement, anyarray, anynonarray, anyenum, anyrange, or anymultirange."),
2925 else if (IsPolymorphicTypeFamily2(ret_type))
2927 /* Otherwise, any family-2 type can be deduced from any other */
2928 for (
int i = 0;
i < nargs;
i++)
2930 if (IsPolymorphicTypeFamily2(declared_arg_types[
i]))
2931 return NULL;
/* OK */
2933 /* Keep this list in sync with IsPolymorphicTypeFamily2! */
2934 return psprintf(
_(
"A result of type %s requires at least one input of type anycompatible, anycompatiblearray, anycompatiblenonarray, anycompatiblerange, or anycompatiblemultirange."),
2938 return NULL;
/* OK, ret_type is not polymorphic */
2942 * check_valid_internal_signature()
2943 * Is a proposed function signature valid per INTERNAL safety rules?
2945 * Returns NULL if OK, or a suitable error message if ret_type is INTERNAL but
2946 * none of the declared arg types are. (It's unsafe to create such a function
2947 * since it would allow invocation of INTERNAL-consuming functions directly
2948 * from SQL.) It's overkill to return the error detail message, since there
2949 * is only one possibility, but we do it like this to keep the API similar to
2950 * check_valid_polymorphic_signature().
2954 const Oid *declared_arg_types,
2957 if (ret_type == INTERNALOID)
2959 for (
int i = 0;
i < nargs;
i++)
2961 if (declared_arg_types[
i] == ret_type)
2962 return NULL;
/* OK */
2964 return pstrdup(
_(
"A result of type internal requires at least one input of type internal."));
2967 return NULL;
/* OK, ret_type is not INTERNAL */
2972 * Assign a category to the specified type OID.
2974 * NB: this must not return TYPCATEGORY_INVALID.
2980 bool typispreferred;
2983 Assert(typcategory != TYPCATEGORY_INVALID);
2989 * Check if this type is a preferred type for the given category.
2991 * If category is TYPCATEGORY_INVALID, then we'll return true for preferred
2992 * types of any category; otherwise, only for preferred types of that
2999 bool typispreferred;
3002 if (category == typcategory || category == TYPCATEGORY_INVALID)
3003 return typispreferred;
3009/* IsBinaryCoercible()
3010 * Check if srctype is binary-coercible to targettype.
3012 * This notion allows us to cheat and directly exchange values without
3013 * going through the trouble of calling a conversion function. Note that
3014 * in general, this should only be an implementation shortcut. Before 7.4,
3015 * this was also used as a heuristic for resolving overloaded functions and
3016 * operators, but that's basically a bad idea.
3018 * As of 7.3, binary coercibility isn't hardwired into the code anymore.
3019 * We consider two types binary-coercible if there is an implicitly
3020 * invokable, no-function-needed pg_cast entry. Also, a domain is always
3021 * binary-coercible to its base type, though *not* vice versa (in the other
3022 * direction, one must apply domain constraint checks before accepting the
3023 * value as legitimate). We also need to special-case various polymorphic
3026 * This function replaces IsBinaryCompatible(), which was an inherently
3027 * symmetric test. Since the pg_cast entries aren't necessarily symmetric,
3028 * the order of the operands is now significant.
3038/* IsBinaryCoercibleWithCast()
3039 * Check if srctype is binary-coercible to targettype.
3041 * This variant also returns the OID of the pg_cast entry if one is involved.
3042 * *castoid is set to InvalidOid if no binary-coercible cast exists, or if
3043 * there is a hard-wired rule for it rather than a pg_cast entry.
3055 /* Fast path if same type */
3056 if (srctype == targettype)
3059 /* Anything is coercible to ANY or ANYELEMENT or ANYCOMPATIBLE */
3060 if (targettype == ANYOID || targettype == ANYELEMENTOID ||
3061 targettype == ANYCOMPATIBLEOID)
3064 /* If srctype is a domain, reduce to its base type */
3068 /* Somewhat-fast path for domain -> base type case */
3069 if (srctype == targettype)
3072 /* Also accept any array type as coercible to ANY[COMPATIBLE]ARRAY */
3073 if (targettype == ANYARRAYOID || targettype == ANYCOMPATIBLEARRAYOID)
3077 /* Also accept any non-array type as coercible to ANY[COMPATIBLE]NONARRAY */
3078 if (targettype == ANYNONARRAYOID || targettype == ANYCOMPATIBLENONARRAYOID)
3082 /* Also accept any enum type as coercible to ANYENUM */
3083 if (targettype == ANYENUMOID)
3087 /* Also accept any range type as coercible to ANY[COMPATIBLE]RANGE */
3088 if (targettype == ANYRANGEOID || targettype == ANYCOMPATIBLERANGEOID)
3092 /* Also, any multirange type is coercible to ANY[COMPATIBLE]MULTIRANGE */
3093 if (targettype == ANYMULTIRANGEOID || targettype == ANYCOMPATIBLEMULTIRANGEOID)
3097 /* Also accept any composite type as coercible to RECORD */
3098 if (targettype == RECORDOID)
3102 /* Also accept any composite array type as coercible to RECORD[] */
3103 if (targettype == RECORDARRAYOID)
3107 /* Else look in pg_cast */
3112 return false;
/* no cast */
3115 result = (castForm->castmethod == COERCION_METHOD_BINARY &&
3116 castForm->castcontext == COERCION_CODE_IMPLICIT);
3119 *castoid = castForm->oid;
3128 * find_coercion_pathway
3129 * Look for a coercion pathway between two types.
3131 * Currently, this deals only with scalar-type cases; it does not consider
3132 * polymorphic types nor casts between composite types. (Perhaps fold
3133 * those in someday?)
3135 * ccontext determines the set of available casts.
3137 * The possible result codes are:
3138 * COERCION_PATH_NONE: failed to find any coercion pathway
3139 * *funcid is set to InvalidOid
3140 * COERCION_PATH_FUNC: apply the coercion function returned in *funcid
3141 * COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
3142 * *funcid is set to InvalidOid
3143 * COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
3144 * *funcid is set to InvalidOid
3145 * COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
3146 * *funcid is set to InvalidOid
3148 * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
3149 * needed to do the coercion; if the target is a domain then we may need to
3150 * apply domain constraint checking. If you want to check for a zero-effort
3151 * conversion then use IsBinaryCoercible().
3163 /* Perhaps the types are domains; if so, look at their base types */
3169 /* Domains are always coercible to and from their base type */
3170 if (sourceTypeId == targetTypeId)
3173 /* Look in pg_cast */
3183 /* convert char value for castcontext to CoercionContext enum */
3184 switch (castForm->castcontext)
3186 case COERCION_CODE_IMPLICIT:
3189 case COERCION_CODE_ASSIGNMENT:
3192 case COERCION_CODE_EXPLICIT:
3196 elog(
ERROR,
"unrecognized castcontext: %d",
3197 (
int) castForm->castcontext);
3198 castcontext = 0;
/* keep compiler quiet */
3202 /* Rely on ordering of enum for correct behavior here */
3203 if (ccontext >= castcontext)
3205 switch (castForm->castmethod)
3207 case COERCION_METHOD_FUNCTION:
3209 *funcid = castForm->castfunc;
3211 case COERCION_METHOD_INOUT:
3214 case COERCION_METHOD_BINARY:
3218 elog(
ERROR,
"unrecognized castmethod: %d",
3219 (
int) castForm->castmethod);
3229 * If there's no pg_cast entry, perhaps we are dealing with a pair of
3230 * array types. If so, and if their element types have a conversion
3231 * pathway, report that we can coerce with an ArrayCoerceExpr.
3233 * Hack: disallow coercions to oidvector and int2vector, which
3234 * otherwise tend to capture coercions that should go to "real" array
3235 * types. We want those types to be considered "real" arrays for many
3236 * purposes, but not this one. (Also, ArrayCoerceExpr isn't
3237 * guaranteed to produce an output that meets the restrictions of
3238 * these datatypes, such as being 1-dimensional.)
3240 if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
3263 * If we still haven't found a possibility, consider automatic casting
3264 * using I/O functions. We allow assignment casts to string types and
3265 * explicit casts from string types to be handled this way. (The
3266 * CoerceViaIO mechanism is a lot more general than that, but this is
3267 * all we want to allow in the absence of a pg_cast entry.) It would
3268 * probably be better to insist on explicit casts in both directions,
3269 * but this is a compromise to preserve something of the pre-8.3
3270 * behavior that many types had implicit (yipes!) casts to text.
3284 * When parsing PL/pgSQL assignments, allow an I/O cast to be used
3285 * whenever no normal coercion is available.
3296 * find_typmod_coercion_function -- does the given type need length coercion?
3298 * If the target type possesses a pg_cast function from itself to itself,
3299 * it must need length coercion.
3301 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
3303 * If the given type is a varlena array type, we do not look for a coercion
3304 * function associated directly with the array type, but instead look for
3305 * one associated with the element type. An ArrayCoerceExpr node must be
3306 * used to apply such a function. (Note: currently, it's pointless to
3307 * return the funcid in this case, because it'll just get looked up again
3308 * in the recursive construction of the ArrayCoerceExpr's elemexpr.)
3310 * We use the same result enum as find_coercion_pathway, but the only possible
3312 * COERCION_PATH_NONE: no length coercion needed
3313 * COERCION_PATH_FUNC: apply the function returned in *funcid
3314 * COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
3331 /* Check for a "true" array type */
3332 if (IsTrueArrayType(typeForm))
3334 /* Yes, switch our attention to the element type */
3335 typeId = typeForm->typelem;
3340 /* Look in pg_cast */
3349 *funcid = castForm->castfunc;
3361 * Is this type an array of composite?
3363 * Note: this will not return true for record[]; check for RECORDARRAYOID
3364 * separately if needed.
3376 * Check whether reltypeId is the row type of a typed table of type
3377 * reloftypeId, or is a domain over such a row type. (This is conceptually
3378 * similar to the subtype relationship checked by typeInheritsFrom().)
3384 bool result =
false;
3393 elog(
ERROR,
"cache lookup failed for relation %u", relid);
3396 if (reltup->reloftype == reloftypeId)
#define InvalidAttrNumber
#define OidIsValid(objectId)
bool datumIsEqual(Datum value1, Datum value2, bool typByVal, int typLen)
int errmsg_internal(const char *fmt,...)
int errdetail(const char *fmt,...)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
#define ereport(elevel,...)
#define PG_DETOAST_DATUM(datum)
Assert(PointerIsAligned(start, uint64))
#define HeapTupleIsValid(tuple)
static void * GETSTRUCT(const HeapTupleData *tuple)
List * lappend(List *list, void *datum)
Oid get_range_subtype(Oid rangeOid)
Oid get_element_type(Oid typid)
bool type_is_range(Oid typid)
bool type_is_enum(Oid typid)
Oid get_multirange_range(Oid multirangeOid)
Oid get_range_multirange(Oid rangeOid)
bool type_is_collatable(Oid typid)
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Oid getBaseType(Oid typid)
Oid get_array_type(Oid typid)
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
bool type_is_multirange(Oid typid)
#define type_is_array(typid)
#define type_is_array_domain(typid)
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
char * pstrdup(const char *in)
Oid exprType(const Node *expr)
int32 exprTypmod(const Node *expr)
Oid exprCollation(const Node *expr)
Node * applyRelabelType(Node *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat, int rlocation, bool overwrite_ok)
int exprLocation(const Node *expr)
bool expression_returns_set(Node *clause)
#define IsA(nodeptr, _type_)
TYPCATEGORY TypeCategory(Oid type)
static bool verify_common_type_from_oids(Oid common_type, int nargs, const Oid *typeids)
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
Node * coerce_to_common_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *context)
static bool typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
static Node * coerce_record_to_complex(ParseState *pstate, Node *node, Oid targetTypeId, CoercionContext ccontext, CoercionForm cformat, int location)
CoercionPathType find_typmod_coercion_function(Oid typeId, Oid *funcid)
static Node * coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod, CoercionContext ccontext, CoercionForm cformat, int location, bool hideInputCoercion)
bool check_generic_type_consistency(const Oid *actual_arg_types, const Oid *declared_arg_types, int nargs)
bool verify_common_type(Oid common_type, List *exprs)
char * check_valid_internal_signature(Oid ret_type, const Oid *declared_arg_types, int nargs)
Node * coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId, CoercionContext ccontext, CoercionForm cformat, int location, bool hideInputCoercion)
char * check_valid_polymorphic_signature(Oid ret_type, const Oid *declared_arg_types, int nargs)
Node * coerce_to_specific_type_typmod(ParseState *pstate, Node *node, Oid targetTypeId, int32 targetTypmod, const char *constructName)
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
int parser_coercion_errposition(ParseState *pstate, int coerce_location, Node *input_expr)
Node * coerce_null_to_domain(Oid typid, int32 typmod, Oid collation, int typlen, bool typbyval)
int32 select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
static Node * build_coercion_expression(Node *node, CoercionPathType pathtype, Oid funcId, Oid targetTypeId, int32 targetTypMod, CoercionContext ccontext, CoercionForm cformat, int location)
Node * coerce_to_specific_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *constructName)
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
static bool is_complex_array(Oid typid)
bool IsBinaryCoercible(Oid srctype, Oid targettype)
bool IsPreferredType(TYPCATEGORY category, Oid type)
static void hide_coercion_node(Node *node)
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
static Oid select_common_type_from_oids(int nargs, const Oid *typeids, bool noerror)
bool IsBinaryCoercibleWithCast(Oid srctype, Oid targettype, Oid *castoid)
@ COERCION_PATH_COERCEVIAIO
@ COERCION_PATH_ARRAYCOERCE
@ COERCION_PATH_RELABELTYPE
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
int parser_errposition(ParseState *pstate, int location)
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
List * expandNSItemVars(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, int location, List **colnames)
ParseNamespaceItem * GetNSItemByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
Oid typeOrDomainTypeRelid(Oid type_id)
Oid typeTypeCollation(Type typ)
char * typeTypeName(Type t)
Datum stringTypeDatum(Type tp, char *string, int32 atttypmod)
#define ISCOMPLEX(typeid)
FormData_pg_attribute * Form_pg_attribute
FormData_pg_cast * Form_pg_cast
FormData_pg_class * Form_pg_class
bool typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId)
#define for_each_cell(cell, lst, initcell)
static ListCell * list_head(const List *l)
static ListCell * list_second_cell(const List *l)
static ListCell * lnext(const List *l, const ListCell *c)
FormData_pg_proc * Form_pg_proc
FormData_pg_type * Form_pg_type
static Datum PointerGetDatum(const void *X)
static Datum BoolGetDatum(bool X)
static Datum ObjectIdGetDatum(Oid X)
static char * DatumGetCString(Datum X)
static Datum Int32GetDatum(int32 X)
char * psprintf(const char *fmt,...)
CoerceParamHook p_coerce_param_hook
void ReleaseSysCache(HeapTuple tuple)
HeapTuple SearchSysCache1(int cacheId, Datum key1)
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
#define ReleaseTupleDesc(tupdesc)
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)