1 /*-------------------------------------------------------------------------
4 * handle type coercions/conversions for parser
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/parser/parse_coerce.c
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_cast.h"
18 #include "catalog/pg_class.h"
19 #include "catalog/pg_inherits_fn.h"
20 #include "catalog/pg_proc.h"
21 #include "catalog/pg_type.h"
22 #include "nodes/makefuncs.h"
23 #include "nodes/nodeFuncs.h"
24 #include "parser/parse_coerce.h"
25 #include "parser/parse_func.h"
26 #include "parser/parse_relation.h"
27 #include "parser/parse_type.h"
28 #include "utils/builtins.h"
29 #include "utils/fmgroids.h"
30 #include "utils/lsyscache.h"
31 #include "utils/syscache.h"
32 #include "utils/typcache.h"
35 static Node *coerce_type_typmod(Node *node,
36 Oid targetTypeId, int32 targetTypMod,
37 CoercionForm cformat, int location,
38 bool isExplicit, bool hideInputCoercion);
39 static void hide_coercion_node(Node *node);
40 static Node *build_coercion_expression(Node *node,
41 CoercionPathType pathtype,
43 Oid targetTypeId, int32 targetTypMod,
44 CoercionForm cformat, int location,
46 static Node *coerce_record_to_complex(ParseState *pstate, Node *node,
48 CoercionContext ccontext,
51 static bool is_complex_array(Oid typid);
52 static bool typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId);
56 * coerce_to_target_type()
57 * Convert an expression to a target type and typmod.
59 * This is the general-purpose entry point for arbitrary type coercion
60 * operations. Direct use of the component operations can_coerce_type,
61 * coerce_type, and coerce_type_typmod should be restricted to special
62 * cases (eg, when the conversion is expected to succeed).
64 * Returns the possibly-transformed expression tree, or NULL if the type
65 * conversion is not possible. (We do this, rather than ereport'ing directly,
66 * so that callers can generate custom error messages indicating context.)
68 * pstate - parse state (can be NULL, see coerce_type)
69 * expr - input expression tree (already transformed by transformExpr)
70 * exprtype - result type of expr
71 * targettype - desired result type
72 * targettypmod - desired result typmod
73 * ccontext, cformat - context indicators to control coercions
74 * location - parse location of the coercion request, or -1 if unknown/implicit
77 coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype,
78 Oid targettype, int32 targettypmod,
79 CoercionContext ccontext,
85 if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
88 result = coerce_type(pstate, expr, exprtype,
89 targettype, targettypmod,
90 ccontext, cformat, location);
93 * If the target is a fixed-length type, it may need a length coercion as
94 * well as a type coercion. If we find ourselves adding both, force the
95 * inner coercion node to implicit display form.
97 result = coerce_type_typmod(result,
98 targettype, targettypmod,
100 (cformat != COERCE_IMPLICIT_CAST),
101 (result != expr && !IsA(result, Const)));
109 * Convert an expression to a different type.
111 * The caller should already have determined that the coercion is possible;
112 * see can_coerce_type.
114 * Normally, no coercion to a typmod (length) is performed here. The caller
115 * must call coerce_type_typmod as well, if a typmod constraint is wanted.
116 * (But if the target type is a domain, it may internally contain a
117 * typmod constraint, which will be applied inside coerce_to_domain.)
118 * In some cases pg_cast specifies a type coercion function that also
119 * applies length conversion, and in those cases only, the result will
120 * already be properly coerced to the specified typmod.
122 * pstate is only used in the case that we are able to resolve the type of
123 * a previously UNKNOWN Param. It is okay to pass pstate = NULL if the
124 * caller does not want type information updated for Params.
126 * Note: this function must not modify the given expression tree, only add
127 * decoration on top of it. See transformSetOperationTree, for example.
130 coerce_type(ParseState *pstate, Node *node,
131 Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
132 CoercionContext ccontext, CoercionForm cformat, int location)
135 CoercionPathType pathtype;
138 if (targetTypeId == inputTypeId ||
141 /* no conversion needed */
144 if (targetTypeId == ANYOID ||
145 targetTypeId == ANYELEMENTOID ||
146 targetTypeId == ANYNONARRAYOID ||
147 (targetTypeId == ANYARRAYOID && inputTypeId != UNKNOWNOID) ||
148 (targetTypeId == ANYENUMOID && inputTypeId != UNKNOWNOID))
151 * Assume can_coerce_type verified that implicit coercion is okay.
153 * Note: by returning the unmodified node here, we are saying that
154 * it's OK to treat an UNKNOWN constant as a valid input for a
155 * function accepting ANY, ANYELEMENT, or ANYNONARRAY. This should be
156 * all right, since an UNKNOWN value is still a perfectly valid Datum.
157 * However an UNKNOWN value is definitely *not* an array, and so we
158 * mustn't accept it for ANYARRAY. (Instead, we will call anyarray_in
159 * below, which will produce an error.) Likewise, UNKNOWN input is no
162 * NB: we do NOT want a RelabelType here.
166 if (inputTypeId == UNKNOWNOID && IsA(node, Const))
169 * Input is a string constant with previously undetermined type. Apply
170 * the target type's typinput function to it to produce a constant of
173 * NOTE: this case cannot be folded together with the other
174 * constant-input case, since the typinput function does not
175 * necessarily behave the same as a type conversion function. For
176 * example, int4's typinput function will reject "1.2", whereas
177 * float-to-int type conversion will round to integer.
179 * XXX if the typinput function is not immutable, we really ought to
180 * postpone evaluation of the function call until runtime. But there
181 * is no way to represent a typinput function call as an expression
182 * tree, because C-string values are not Datums. (XXX This *is*
183 * possible as of 7.3, do we want to do it?)
185 Const *con = (Const *) node;
186 Const *newcon = makeNode(Const);
191 ParseCallbackState pcbstate;
194 * If the target type is a domain, we want to call its base type's
195 * input routine, not domain_in(). This is to avoid premature failure
196 * when the domain applies a typmod: existing input routines follow
197 * implicit-coercion semantics for length checks, which is not always
198 * what we want here. The needed check will be applied properly
199 * inside coerce_to_domain().
201 baseTypeMod = targetTypeMod;
202 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
205 * For most types we pass typmod -1 to the input routine, because
206 * existing input routines follow implicit-coercion semantics for
207 * length checks, which is not always what we want here. Any length
208 * constraint will be applied later by our caller. An exception
209 * however is the INTERVAL type, for which we *must* pass the typmod
210 * or it won't be able to obey the bizarre SQL-spec input rules. (Ugly
211 * as sin, but so is this part of the spec...)
213 if (baseTypeId == INTERVALOID)
214 inputTypeMod = baseTypeMod;
218 targetType = typeidType(baseTypeId);
220 newcon->consttype = baseTypeId;
221 newcon->consttypmod = inputTypeMod;
222 newcon->constcollid = get_typcollation(newcon->consttype);
223 newcon->constlen = typeLen(targetType);
224 newcon->constbyval = typeByVal(targetType);
225 newcon->constisnull = con->constisnull;
226 /* Use the leftmost of the constant's and coercion's locations */
228 newcon->location = con->location;
229 else if (con->location >= 0 && con->location < location)
230 newcon->location = con->location;
232 newcon->location = location;
235 * Set up to point at the constant's text if the input routine throws
238 setup_parser_errposition_callback(&pcbstate, pstate, con->location);
241 * We assume here that UNKNOWN's internal representation is the same
244 if (!con->constisnull)
245 newcon->constvalue = stringTypeDatum(targetType,
246 DatumGetCString(con->constvalue),
249 newcon->constvalue = stringTypeDatum(targetType,
253 cancel_parser_errposition_callback(&pcbstate);
255 result = (Node *) newcon;
257 /* If target is a domain, apply constraints. */
258 if (baseTypeId != targetTypeId)
259 result = coerce_to_domain(result,
260 baseTypeId, baseTypeMod,
262 cformat, location, false, false);
264 ReleaseSysCache(targetType);
268 if (IsA(node, Param) &&
269 pstate != NULL && pstate->p_coerce_param_hook != NULL)
272 * Allow the CoerceParamHook to decide what happens. It can return a
273 * transformed node (very possibly the same Param node), or return
274 * NULL to indicate we should proceed with normal coercion.
276 result = (*pstate->p_coerce_param_hook) (pstate,
284 if (IsA(node, CollateExpr))
287 * If we have a COLLATE clause, we have to push the coercion
288 * underneath the COLLATE. This is really ugly, but there is little
289 * choice because the above hacks on Consts and Params wouldn't happen
292 CollateExpr *coll = (CollateExpr *) node;
293 CollateExpr *newcoll = makeNode(CollateExpr);
295 newcoll->arg = (Expr *)
296 coerce_type(pstate, (Node *) coll->arg,
297 inputTypeId, targetTypeId, targetTypeMod,
298 ccontext, cformat, location);
299 newcoll->collOid = coll->collOid;
300 newcoll->location = coll->location;
301 return (Node *) newcoll;
303 pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
305 if (pathtype != COERCION_PATH_NONE)
307 if (pathtype != COERCION_PATH_RELABELTYPE)
310 * Generate an expression tree representing run-time application
311 * of the conversion function. If we are dealing with a domain
312 * target type, the conversion function will yield the base type,
313 * and we need to extract the correct typmod to use from the
314 * domain's typtypmod.
319 baseTypeMod = targetTypeMod;
320 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
322 result = build_coercion_expression(node, pathtype, funcId,
323 baseTypeId, baseTypeMod,
325 (cformat != COERCE_IMPLICIT_CAST));
328 * If domain, coerce to the domain type and relabel with domain
329 * type ID. We can skip the internal length-coercion step if the
330 * selected coercion function was a type-and-length coercion.
332 if (targetTypeId != baseTypeId)
333 result = coerce_to_domain(result, baseTypeId, baseTypeMod,
335 cformat, location, true,
336 exprIsLengthCoercion(result,
342 * We don't need to do a physical conversion, but we do need to
343 * attach a RelabelType node so that the expression will be seen
344 * to have the intended type when inspected by higher-level code.
346 * Also, domains may have value restrictions beyond the base type
347 * that must be accounted for. If the destination is a domain
348 * then we won't need a RelabelType node.
350 result = coerce_to_domain(node, InvalidOid, -1, targetTypeId,
351 cformat, location, false, false);
355 * XXX could we label result with exprTypmod(node) instead of
356 * default -1 typmod, to save a possible length-coercion
357 * later? Would work if both types have same interpretation of
358 * typmod, which is likely but not certain.
360 RelabelType *r = makeRelabelType((Expr *) result,
365 r->location = location;
371 if (inputTypeId == RECORDOID &&
372 ISCOMPLEX(targetTypeId))
374 /* Coerce a RECORD to a specific complex type */
375 return coerce_record_to_complex(pstate, node, targetTypeId,
376 ccontext, cformat, location);
378 if (targetTypeId == RECORDOID &&
379 ISCOMPLEX(inputTypeId))
381 /* Coerce a specific complex type to RECORD */
382 /* NB: we do NOT want a RelabelType here */
386 if (inputTypeId == RECORDARRAYOID &&
387 is_complex_array(targetTypeId))
389 /* Coerce record[] to a specific complex array type */
390 /* not implemented yet ... */
393 if (targetTypeId == RECORDARRAYOID &&
394 is_complex_array(inputTypeId))
396 /* Coerce a specific complex array type to record[] */
397 /* NB: we do NOT want a RelabelType here */
400 if (typeInheritsFrom(inputTypeId, targetTypeId)
401 || typeIsOfTypedTable(inputTypeId, targetTypeId))
404 * Input class type is a subclass of target, so generate an
405 * appropriate runtime conversion (removing unneeded columns and
406 * possibly rearranging the ones that are wanted).
408 ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
410 r->arg = (Expr *) node;
411 r->resulttype = targetTypeId;
412 r->convertformat = cformat;
413 r->location = location;
416 /* If we get here, caller blew it */
417 elog(ERROR, "failed to find conversion function from %s to %s",
418 format_type_be(inputTypeId), format_type_be(targetTypeId));
419 return NULL; /* keep compiler quiet */
425 * Can input_typeids be coerced to target_typeids?
427 * We must be told the context (CAST construct, assignment, implicit coercion)
428 * as this determines the set of available casts.
431 can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids,
432 CoercionContext ccontext)
434 bool have_generics = false;
437 /* run through argument list... */
438 for (i = 0; i < nargs; i++)
440 Oid inputTypeId = input_typeids[i];
441 Oid targetTypeId = target_typeids[i];
442 CoercionPathType pathtype;
445 /* no problem if same type */
446 if (inputTypeId == targetTypeId)
449 /* accept if target is ANY */
450 if (targetTypeId == ANYOID)
453 /* accept if target is polymorphic, for now */
454 if (IsPolymorphicType(targetTypeId))
456 have_generics = true; /* do more checking later */
461 * If input is an untyped string constant, assume we can convert it to
464 if (inputTypeId == UNKNOWNOID)
468 * If pg_cast shows that we can coerce, accept. This test now covers
469 * both binary-compatible and coercion-function cases.
471 pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
473 if (pathtype != COERCION_PATH_NONE)
477 * If input is RECORD and target is a composite type, assume we can
478 * coerce (may need tighter checking here)
480 if (inputTypeId == RECORDOID &&
481 ISCOMPLEX(targetTypeId))
485 * If input is a composite type and target is RECORD, accept
487 if (targetTypeId == RECORDOID &&
488 ISCOMPLEX(inputTypeId))
491 #ifdef NOT_USED /* not implemented yet */
494 * If input is record[] and target is a composite array type, assume
495 * we can coerce (may need tighter checking here)
497 if (inputTypeId == RECORDARRAYOID &&
498 is_complex_array(targetTypeId))
503 * If input is a composite array type and target is record[], accept
505 if (targetTypeId == RECORDARRAYOID &&
506 is_complex_array(inputTypeId))
510 * If input is a class type that inherits from target, accept
512 if (typeInheritsFrom(inputTypeId, targetTypeId)
513 || typeIsOfTypedTable(inputTypeId, targetTypeId))
517 * Else, cannot coerce at this argument position
522 /* If we found any generic argument types, cross-check them */
525 if (!check_generic_type_consistency(input_typeids, target_typeids,
535 * Create an expression tree to represent coercion to a domain type.
537 * 'arg': input expression
538 * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
539 * has not bothered to look this up)
540 * 'baseTypeMod': base type typmod of domain, if known (pass -1 if caller
541 * has not bothered to look this up)
542 * 'typeId': target type to coerce to
543 * 'cformat': coercion format
544 * 'location': coercion request location
545 * 'hideInputCoercion': if true, hide the input coercion under this one.
546 * 'lengthCoercionDone': if true, caller already accounted for length,
547 * ie the input is already of baseTypMod as well as baseTypeId.
549 * If the target type isn't a domain, the given 'arg' is returned as-is.
552 coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId,
553 CoercionForm cformat, int location,
554 bool hideInputCoercion,
555 bool lengthCoercionDone)
557 CoerceToDomain *result;
559 /* Get the base type if it hasn't been supplied */
560 if (baseTypeId == InvalidOid)
561 baseTypeId = getBaseTypeAndTypmod(typeId, &baseTypeMod);
563 /* If it isn't a domain, return the node as it was passed in */
564 if (baseTypeId == typeId)
567 /* Suppress display of nested coercion steps */
568 if (hideInputCoercion)
569 hide_coercion_node(arg);
572 * If the domain applies a typmod to its base type, build the appropriate
573 * coercion step. Mark it implicit for display purposes, because we don't
574 * want it shown separately by ruleutils.c; but the isExplicit flag passed
575 * to the conversion function depends on the manner in which the domain
576 * coercion is invoked, so that the semantics of implicit and explicit
577 * coercion differ. (Is that really the behavior we want?)
579 * NOTE: because we apply this as part of the fixed expression structure,
580 * ALTER DOMAIN cannot alter the typtypmod. But it's unclear that that
581 * would be safe to do anyway, without lots of knowledge about what the
582 * base type thinks the typmod means.
584 if (!lengthCoercionDone)
586 if (baseTypeMod >= 0)
587 arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
588 COERCE_IMPLICIT_CAST, location,
589 (cformat != COERCE_IMPLICIT_CAST),
594 * Now build the domain coercion node. This represents run-time checking
595 * of any constraints currently attached to the domain. This also ensures
596 * that the expression is properly labeled as to result type.
598 result = makeNode(CoerceToDomain);
599 result->arg = (Expr *) arg;
600 result->resulttype = typeId;
601 result->resulttypmod = -1; /* currently, always -1 for domains */
602 /* resultcollid will be set by parse_collate.c */
603 result->coercionformat = cformat;
604 result->location = location;
606 return (Node *) result;
611 * coerce_type_typmod()
612 * Force a value to a particular typmod, if meaningful and possible.
614 * This is applied to values that are going to be stored in a relation
615 * (where we have an atttypmod for the column) as well as values being
616 * explicitly CASTed (where the typmod comes from the target type spec).
618 * The caller must have already ensured that the value is of the correct
619 * type, typically by applying coerce_type.
621 * cformat determines the display properties of the generated node (if any),
622 * while isExplicit may affect semantics. If hideInputCoercion is true
623 * *and* we generate a node, the input node is forced to IMPLICIT display
624 * form, so that only the typmod coercion node will be visible when
625 * displaying the expression.
627 * NOTE: this does not need to work on domain types, because any typmod
628 * coercion for a domain is considered to be part of the type coercion
629 * needed to produce the domain value in the first place. So, no getBaseType.
632 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
633 CoercionForm cformat, int location,
634 bool isExplicit, bool hideInputCoercion)
636 CoercionPathType pathtype;
640 * A negative typmod is assumed to mean that no coercion is wanted. Also,
641 * skip coercion if already done.
643 if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
646 pathtype = find_typmod_coercion_function(targetTypeId, &funcId);
648 if (pathtype != COERCION_PATH_NONE)
650 /* Suppress display of nested coercion steps */
651 if (hideInputCoercion)
652 hide_coercion_node(node);
654 node = build_coercion_expression(node, pathtype, funcId,
655 targetTypeId, targetTypMod,
664 * Mark a coercion node as IMPLICIT so it will never be displayed by
665 * ruleutils.c. We use this when we generate a nest of coercion nodes
666 * to implement what is logically one conversion; the inner nodes are
667 * forced to IMPLICIT_CAST format. This does not change their semantics,
668 * only display behavior.
670 * It is caller error to call this on something that doesn't have a
671 * CoercionForm field.
674 hide_coercion_node(Node *node)
676 if (IsA(node, FuncExpr))
677 ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
678 else if (IsA(node, RelabelType))
679 ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
680 else if (IsA(node, CoerceViaIO))
681 ((CoerceViaIO *) node)->coerceformat = COERCE_IMPLICIT_CAST;
682 else if (IsA(node, ArrayCoerceExpr))
683 ((ArrayCoerceExpr *) node)->coerceformat = COERCE_IMPLICIT_CAST;
684 else if (IsA(node, ConvertRowtypeExpr))
685 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
686 else if (IsA(node, RowExpr))
687 ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
688 else if (IsA(node, CoerceToDomain))
689 ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
691 elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
695 * build_coercion_expression()
696 * Construct an expression tree for applying a pg_cast entry.
698 * This is used for both type-coercion and length-coercion operations,
699 * since there is no difference in terms of the calling convention.
702 build_coercion_expression(Node *node,
703 CoercionPathType pathtype,
705 Oid targetTypeId, int32 targetTypMod,
706 CoercionForm cformat, int location,
711 if (OidIsValid(funcId))
714 Form_pg_proc procstruct;
716 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcId));
717 if (!HeapTupleIsValid(tp))
718 elog(ERROR, "cache lookup failed for function %u", funcId);
719 procstruct = (Form_pg_proc) GETSTRUCT(tp);
722 * These Asserts essentially check that function is a legal coercion
723 * function. We can't make the seemingly obvious tests on prorettype
724 * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
725 * various binary-compatibility cases.
727 /* Assert(targetTypeId == procstruct->prorettype); */
728 Assert(!procstruct->proretset);
729 Assert(!procstruct->proisagg);
730 Assert(!procstruct->proiswindow);
731 nargs = procstruct->pronargs;
732 Assert(nargs >= 1 && nargs <= 3);
733 /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
734 Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
735 Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
740 if (pathtype == COERCION_PATH_FUNC)
742 /* We build an ordinary FuncExpr with special arguments */
747 Assert(OidIsValid(funcId));
749 args = list_make1(node);
753 /* Pass target typmod as an int4 constant */
754 cons = makeConst(INT4OID,
757 Int32GetDatum(targetTypMod),
761 args = lappend(args, cons);
766 /* Pass it a boolean isExplicit parameter, too */
767 cons = makeConst(BOOLOID,
770 BoolGetDatum(isExplicit),
774 args = lappend(args, cons);
777 fexpr = makeFuncExpr(funcId, targetTypeId, args,
778 InvalidOid, InvalidOid, cformat);
779 fexpr->location = location;
780 return (Node *) fexpr;
782 else if (pathtype == COERCION_PATH_ARRAYCOERCE)
784 /* We need to build an ArrayCoerceExpr */
785 ArrayCoerceExpr *acoerce = makeNode(ArrayCoerceExpr);
787 acoerce->arg = (Expr *) node;
788 acoerce->elemfuncid = funcId;
789 acoerce->resulttype = targetTypeId;
792 * Label the output as having a particular typmod only if we are
793 * really invoking a length-coercion function, ie one with more than
796 acoerce->resulttypmod = (nargs >= 2) ? targetTypMod : -1;
797 acoerce->isExplicit = isExplicit;
798 acoerce->coerceformat = cformat;
799 acoerce->location = location;
801 return (Node *) acoerce;
803 else if (pathtype == COERCION_PATH_COERCEVIAIO)
805 /* We need to build a CoerceViaIO node */
806 CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
808 Assert(!OidIsValid(funcId));
810 iocoerce->arg = (Expr *) node;
811 iocoerce->resulttype = targetTypeId;
812 iocoerce->coerceformat = cformat;
813 iocoerce->location = location;
815 return (Node *) iocoerce;
819 elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
821 return NULL; /* keep compiler quiet */
827 * coerce_record_to_complex
828 * Coerce a RECORD to a specific composite type.
830 * Currently we only support this for inputs that are RowExprs or whole-row
834 coerce_record_to_complex(ParseState *pstate, Node *node,
836 CoercionContext ccontext,
837 CoercionForm cformat,
848 if (node && IsA(node, RowExpr))
851 * Since the RowExpr must be of type RECORD, we needn't worry about it
852 * containing any dropped columns.
854 args = ((RowExpr *) node)->args;
856 else if (node && IsA(node, Var) &&
857 ((Var *) node)->varattno == InvalidAttrNumber)
859 int rtindex = ((Var *) node)->varno;
860 int sublevels_up = ((Var *) node)->varlevelsup;
861 int vlocation = ((Var *) node)->location;
864 rte = GetRTEByRangeTablePosn(pstate, rtindex, sublevels_up);
865 expandRTE(rte, rtindex, sublevels_up, vlocation, false,
870 (errcode(ERRCODE_CANNOT_COERCE),
871 errmsg("cannot cast type %s to %s",
872 format_type_be(RECORDOID),
873 format_type_be(targetTypeId)),
874 parser_coercion_errposition(pstate, location, node)));
876 tupdesc = lookup_rowtype_tupdesc(targetTypeId, -1);
879 arg = list_head(args);
880 for (i = 0; i < tupdesc->natts; i++)
886 /* Fill in NULLs for dropped columns in rowtype */
887 if (tupdesc->attrs[i]->attisdropped)
890 * can't use atttypid here, but it doesn't really matter what type
891 * the Const claims to be.
893 newargs = lappend(newargs, makeNullConst(INT4OID, -1));
899 (errcode(ERRCODE_CANNOT_COERCE),
900 errmsg("cannot cast type %s to %s",
901 format_type_be(RECORDOID),
902 format_type_be(targetTypeId)),
903 errdetail("Input has too few columns."),
904 parser_coercion_errposition(pstate, location, node)));
905 expr = (Node *) lfirst(arg);
906 exprtype = exprType(expr);
908 cexpr = coerce_to_target_type(pstate,
910 tupdesc->attrs[i]->atttypid,
911 tupdesc->attrs[i]->atttypmod,
913 COERCE_IMPLICIT_CAST,
917 (errcode(ERRCODE_CANNOT_COERCE),
918 errmsg("cannot cast type %s to %s",
919 format_type_be(RECORDOID),
920 format_type_be(targetTypeId)),
921 errdetail("Cannot cast type %s to %s in column %d.",
922 format_type_be(exprtype),
923 format_type_be(tupdesc->attrs[i]->atttypid),
925 parser_coercion_errposition(pstate, location, expr)));
926 newargs = lappend(newargs, cexpr);
932 (errcode(ERRCODE_CANNOT_COERCE),
933 errmsg("cannot cast type %s to %s",
934 format_type_be(RECORDOID),
935 format_type_be(targetTypeId)),
936 errdetail("Input has too many columns."),
937 parser_coercion_errposition(pstate, location, node)));
939 ReleaseTupleDesc(tupdesc);
941 rowexpr = makeNode(RowExpr);
942 rowexpr->args = newargs;
943 rowexpr->row_typeid = targetTypeId;
944 rowexpr->row_format = cformat;
945 rowexpr->colnames = NIL; /* not needed for named target type */
946 rowexpr->location = location;
947 return (Node *) rowexpr;
951 * coerce_to_boolean()
952 * Coerce an argument of a construct that requires boolean input
953 * (AND, OR, NOT, etc). Also check that input is not a set.
955 * Returns the possibly-transformed node tree.
957 * As with coerce_type, pstate may be NULL if no special unknown-Param
958 * processing is wanted.
961 coerce_to_boolean(ParseState *pstate, Node *node,
962 const char *constructName)
964 Oid inputTypeId = exprType(node);
966 if (inputTypeId != BOOLOID)
970 newnode = coerce_to_target_type(pstate, node, inputTypeId,
973 COERCE_IMPLICIT_CAST,
977 (errcode(ERRCODE_DATATYPE_MISMATCH),
978 /* translator: first %s is name of a SQL construct, eg WHERE */
979 errmsg("argument of %s must be type boolean, not type %s",
980 constructName, format_type_be(inputTypeId)),
981 parser_errposition(pstate, exprLocation(node))));
985 if (expression_returns_set(node))
987 (errcode(ERRCODE_DATATYPE_MISMATCH),
988 /* translator: %s is name of a SQL construct, eg WHERE */
989 errmsg("argument of %s must not return a set",
991 parser_errposition(pstate, exprLocation(node))));
997 * coerce_to_specific_type()
998 * Coerce an argument of a construct that requires a specific data type.
999 * Also check that input is not a set.
1001 * Returns the possibly-transformed node tree.
1003 * As with coerce_type, pstate may be NULL if no special unknown-Param
1004 * processing is wanted.
1007 coerce_to_specific_type(ParseState *pstate, Node *node,
1009 const char *constructName)
1011 Oid inputTypeId = exprType(node);
1013 if (inputTypeId != targetTypeId)
1017 newnode = coerce_to_target_type(pstate, node, inputTypeId,
1019 COERCION_ASSIGNMENT,
1020 COERCE_IMPLICIT_CAST,
1022 if (newnode == NULL)
1024 (errcode(ERRCODE_DATATYPE_MISMATCH),
1025 /* translator: first %s is name of a SQL construct, eg LIMIT */
1026 errmsg("argument of %s must be type %s, not type %s",
1028 format_type_be(targetTypeId),
1029 format_type_be(inputTypeId)),
1030 parser_errposition(pstate, exprLocation(node))));
1034 if (expression_returns_set(node))
1036 (errcode(ERRCODE_DATATYPE_MISMATCH),
1037 /* translator: %s is name of a SQL construct, eg LIMIT */
1038 errmsg("argument of %s must not return a set",
1040 parser_errposition(pstate, exprLocation(node))));
1047 * parser_coercion_errposition - report coercion error location, if possible
1049 * We prefer to point at the coercion request (CAST, ::, etc) if possible;
1050 * but there may be no such location in the case of an implicit coercion.
1051 * In that case point at the input expression.
1053 * XXX possibly this is more generally useful than coercion errors;
1054 * if so, should rename and place with parser_errposition.
1057 parser_coercion_errposition(ParseState *pstate,
1058 int coerce_location,
1061 if (coerce_location >= 0)
1062 return parser_errposition(pstate, coerce_location);
1064 return parser_errposition(pstate, exprLocation(input_expr));
1069 * select_common_type()
1070 * Determine the common supertype of a list of input expressions.
1071 * This is used for determining the output type of CASE, UNION,
1072 * and similar constructs.
1074 * 'exprs' is a *nonempty* list of expressions. Note that earlier items
1075 * in the list will be preferred if there is doubt.
1076 * 'context' is a phrase to use in the error message if we fail to select
1077 * a usable type. Pass NULL to have the routine return InvalidOid
1078 * rather than throwing an error on failure.
1079 * 'which_expr': if not NULL, receives a pointer to the particular input
1080 * expression from which the result type was taken.
1083 select_common_type(ParseState *pstate, List *exprs, const char *context,
1088 TYPCATEGORY pcategory;
1092 Assert(exprs != NIL);
1093 pexpr = (Node *) linitial(exprs);
1094 lc = lnext(list_head(exprs));
1095 ptype = exprType(pexpr);
1098 * If all input types are valid and exactly the same, just pick that type.
1099 * This is the only way that we will resolve the result as being a domain
1100 * type; otherwise domains are smashed to their base types for comparison.
1102 if (ptype != UNKNOWNOID)
1104 for_each_cell(lc, lc)
1106 Node *nexpr = (Node *) lfirst(lc);
1107 Oid ntype = exprType(nexpr);
1112 if (lc == NULL) /* got to the end of the list? */
1115 *which_expr = pexpr;
1121 * Nope, so set up for the full algorithm. Note that at this point, lc
1122 * points to the first list item with type different from pexpr's; we need
1123 * not re-examine any items the previous loop advanced over.
1125 ptype = getBaseType(ptype);
1126 get_type_category_preferred(ptype, &pcategory, &pispreferred);
1128 for_each_cell(lc, lc)
1130 Node *nexpr = (Node *) lfirst(lc);
1131 Oid ntype = getBaseType(exprType(nexpr));
1133 /* move on to next one if no new information... */
1134 if (ntype != UNKNOWNOID && ntype != ptype)
1136 TYPCATEGORY ncategory;
1139 get_type_category_preferred(ntype, &ncategory, &nispreferred);
1140 if (ptype == UNKNOWNOID)
1142 /* so far, only unknowns so take anything... */
1145 pcategory = ncategory;
1146 pispreferred = nispreferred;
1148 else if (ncategory != pcategory)
1151 * both types in different categories? then not much hope...
1153 if (context == NULL)
1156 (errcode(ERRCODE_DATATYPE_MISMATCH),
1158 translator: first %s is name of a SQL construct, eg CASE */
1159 errmsg("%s types %s and %s cannot be matched",
1161 format_type_be(ptype),
1162 format_type_be(ntype)),
1163 parser_errposition(pstate, exprLocation(nexpr))));
1165 else if (!pispreferred &&
1166 can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1167 !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1170 * take new type if can coerce to it implicitly but not the
1171 * other way; but if we have a preferred type, stay on it.
1175 pcategory = ncategory;
1176 pispreferred = nispreferred;
1182 * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1183 * then resolve as type TEXT. This situation comes up with constructs
1184 * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1185 * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1186 * output type as UNKNOWN, but that really doesn't work, because we'd
1187 * probably end up needing a runtime coercion from UNKNOWN to something
1188 * else, and we usually won't have it. We need to coerce the unknown
1189 * literals while they are still literals, so a decision has to be made
1192 if (ptype == UNKNOWNOID)
1196 *which_expr = pexpr;
1201 * coerce_to_common_type()
1202 * Coerce an expression to the given type.
1204 * This is used following select_common_type() to coerce the individual
1205 * expressions to the desired type. 'context' is a phrase to use in the
1206 * error message if we fail to coerce.
1208 * As with coerce_type, pstate may be NULL if no special unknown-Param
1209 * processing is wanted.
1212 coerce_to_common_type(ParseState *pstate, Node *node,
1213 Oid targetTypeId, const char *context)
1215 Oid inputTypeId = exprType(node);
1217 if (inputTypeId == targetTypeId)
1218 return node; /* no work */
1219 if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
1220 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1221 COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
1224 (errcode(ERRCODE_CANNOT_COERCE),
1225 /* translator: first %s is name of a SQL construct, eg CASE */
1226 errmsg("%s could not convert type %s to %s",
1228 format_type_be(inputTypeId),
1229 format_type_be(targetTypeId)),
1230 parser_errposition(pstate, exprLocation(node))));
1235 * check_generic_type_consistency()
1236 * Are the actual arguments potentially compatible with a
1237 * polymorphic function?
1239 * The argument consistency rules are:
1241 * 1) All arguments declared ANYARRAY must have matching datatypes,
1242 * and must in fact be varlena arrays.
1243 * 2) All arguments declared ANYELEMENT must have matching datatypes.
1244 * 3) If there are arguments of both ANYELEMENT and ANYARRAY, make sure
1245 * the actual ANYELEMENT datatype is in fact the element type for
1246 * the actual ANYARRAY datatype.
1247 * 4) ANYENUM is treated the same as ANYELEMENT except that if it is used
1248 * (alone or in combination with plain ANYELEMENT), we add the extra
1249 * condition that the ANYELEMENT type must be an enum.
1250 * 5) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1251 * we add the extra condition that the ANYELEMENT type must not be an array.
1252 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1253 * is an extra restriction if not.)
1255 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1256 * argument, assume it is okay.
1258 * If an input is of type ANYARRAY (ie, we know it's an array, but not
1259 * what element type), we will accept it as a match to an argument declared
1260 * ANYARRAY, so long as we don't have to determine an element type ---
1261 * that is, so long as there is no use of ANYELEMENT. This is mostly for
1262 * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
1264 * We do not ereport here, but just return FALSE if a rule is violated.
1267 check_generic_type_consistency(Oid *actual_arg_types,
1268 Oid *declared_arg_types,
1272 Oid elem_typeid = InvalidOid;
1273 Oid array_typeid = InvalidOid;
1275 bool have_anyelement = false;
1276 bool have_anynonarray = false;
1277 bool have_anyenum = false;
1280 * Loop through the arguments to see if we have any that are polymorphic.
1281 * If so, require the actual types to be consistent.
1283 for (j = 0; j < nargs; j++)
1285 Oid decl_type = declared_arg_types[j];
1286 Oid actual_type = actual_arg_types[j];
1288 if (decl_type == ANYELEMENTOID ||
1289 decl_type == ANYNONARRAYOID ||
1290 decl_type == ANYENUMOID)
1292 have_anyelement = true;
1293 if (decl_type == ANYNONARRAYOID)
1294 have_anynonarray = true;
1295 else if (decl_type == ANYENUMOID)
1296 have_anyenum = true;
1297 if (actual_type == UNKNOWNOID)
1299 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1301 elem_typeid = actual_type;
1303 else if (decl_type == ANYARRAYOID)
1305 if (actual_type == UNKNOWNOID)
1307 if (OidIsValid(array_typeid) && actual_type != array_typeid)
1309 array_typeid = actual_type;
1313 /* Get the element type based on the array type, if we have one */
1314 if (OidIsValid(array_typeid))
1316 if (array_typeid == ANYARRAYOID)
1318 /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1319 if (have_anyelement)
1324 array_typelem = get_element_type(array_typeid);
1325 if (!OidIsValid(array_typelem))
1326 return false; /* should be an array, but isn't */
1328 if (!OidIsValid(elem_typeid))
1331 * if we don't have an element type yet, use the one we just got
1333 elem_typeid = array_typelem;
1335 else if (array_typelem != elem_typeid)
1337 /* otherwise, they better match */
1342 if (have_anynonarray)
1344 /* require the element type to not be an array */
1345 if (type_is_array(elem_typeid))
1351 /* require the element type to be an enum */
1352 if (!type_is_enum(elem_typeid))
1361 * enforce_generic_type_consistency()
1362 * Make sure a polymorphic function is legally callable, and
1363 * deduce actual argument and result types.
1365 * If any polymorphic pseudotype is used in a function's arguments or
1366 * return type, we make sure the actual data types are consistent with
1367 * each other. The argument consistency rules are shown above for
1368 * check_generic_type_consistency().
1370 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1371 * argument, we attempt to deduce the actual type it should have. If
1372 * successful, we alter that position of declared_arg_types[] so that
1373 * make_fn_arguments will coerce the literal to the right thing.
1375 * Rules are applied to the function's return type (possibly altering it)
1376 * if it is declared as a polymorphic type:
1378 * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1379 * argument's actual type as the function's return type.
1380 * 2) If return type is ANYARRAY, no argument is ANYARRAY, but any argument
1381 * is ANYELEMENT, use the actual type of the argument to determine
1382 * the function's return type, i.e. the element type's corresponding
1384 * 3) If return type is ANYARRAY, no argument is ANYARRAY or ANYELEMENT,
1385 * generate an ERROR. This condition is prevented by CREATE FUNCTION
1386 * and is therefore not expected here.
1387 * 4) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1388 * argument's actual type as the function's return type.
1389 * 5) If return type is ANYELEMENT, no argument is ANYELEMENT, but any
1390 * argument is ANYARRAY, use the actual type of the argument to determine
1391 * the function's return type, i.e. the array type's corresponding
1393 * 6) If return type is ANYELEMENT, no argument is ANYARRAY or ANYELEMENT,
1394 * generate an ERROR. This condition is prevented by CREATE FUNCTION
1395 * and is therefore not expected here.
1396 * 7) ANYENUM is treated the same as ANYELEMENT except that if it is used
1397 * (alone or in combination with plain ANYELEMENT), we add the extra
1398 * condition that the ANYELEMENT type must be an enum.
1399 * 8) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1400 * we add the extra condition that the ANYELEMENT type must not be an array.
1401 * (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1402 * is an extra restriction if not.)
1404 * When allow_poly is false, we are not expecting any of the actual_arg_types
1405 * to be polymorphic, and we should not return a polymorphic result type
1406 * either. When allow_poly is true, it is okay to have polymorphic "actual"
1407 * arg types, and we can return ANYARRAY or ANYELEMENT as the result. (This
1408 * case is currently used only to check compatibility of an aggregate's
1409 * declaration with the underlying transfn.)
1411 * A special case is that we could see ANYARRAY as an actual_arg_type even
1412 * when allow_poly is false (this is possible only because pg_statistic has
1413 * columns shown as anyarray in the catalogs). We allow this to match a
1414 * declared ANYARRAY argument, but only if there is no ANYELEMENT argument
1415 * or result (since we can't determine a specific element type to match to
1416 * ANYELEMENT). Note this means that functions taking ANYARRAY had better
1417 * behave sanely if applied to the pg_statistic columns; they can't just
1418 * assume that successive inputs are of the same actual element type.
1421 enforce_generic_type_consistency(Oid *actual_arg_types,
1422 Oid *declared_arg_types,
1428 bool have_generics = false;
1429 bool have_unknowns = false;
1430 Oid elem_typeid = InvalidOid;
1431 Oid array_typeid = InvalidOid;
1433 bool have_anyelement = (rettype == ANYELEMENTOID ||
1434 rettype == ANYNONARRAYOID ||
1435 rettype == ANYENUMOID);
1436 bool have_anynonarray = (rettype == ANYNONARRAYOID);
1437 bool have_anyenum = (rettype == ANYENUMOID);
1440 * Loop through the arguments to see if we have any that are polymorphic.
1441 * If so, require the actual types to be consistent.
1443 for (j = 0; j < nargs; j++)
1445 Oid decl_type = declared_arg_types[j];
1446 Oid actual_type = actual_arg_types[j];
1448 if (decl_type == ANYELEMENTOID ||
1449 decl_type == ANYNONARRAYOID ||
1450 decl_type == ANYENUMOID)
1452 have_generics = have_anyelement = true;
1453 if (decl_type == ANYNONARRAYOID)
1454 have_anynonarray = true;
1455 else if (decl_type == ANYENUMOID)
1456 have_anyenum = true;
1457 if (actual_type == UNKNOWNOID)
1459 have_unknowns = true;
1462 if (allow_poly && decl_type == actual_type)
1463 continue; /* no new information here */
1464 if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1466 (errcode(ERRCODE_DATATYPE_MISMATCH),
1467 errmsg("arguments declared \"anyelement\" are not all alike"),
1468 errdetail("%s versus %s",
1469 format_type_be(elem_typeid),
1470 format_type_be(actual_type))));
1471 elem_typeid = actual_type;
1473 else if (decl_type == ANYARRAYOID)
1475 have_generics = 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(array_typeid) && actual_type != array_typeid)
1485 (errcode(ERRCODE_DATATYPE_MISMATCH),
1486 errmsg("arguments declared \"anyarray\" are not all alike"),
1487 errdetail("%s versus %s",
1488 format_type_be(array_typeid),
1489 format_type_be(actual_type))));
1490 array_typeid = actual_type;
1495 * Fast Track: if none of the arguments are polymorphic, return the
1496 * unmodified rettype. We assume it can't be polymorphic either.
1501 /* Get the element type based on the array type, if we have one */
1502 if (OidIsValid(array_typeid))
1504 if (array_typeid == ANYARRAYOID && !have_anyelement)
1506 /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1507 array_typelem = InvalidOid;
1511 array_typelem = get_element_type(array_typeid);
1512 if (!OidIsValid(array_typelem))
1514 (errcode(ERRCODE_DATATYPE_MISMATCH),
1515 errmsg("argument declared \"anyarray\" is not an array but type %s",
1516 format_type_be(array_typeid))));
1519 if (!OidIsValid(elem_typeid))
1522 * if we don't have an element type yet, use the one we just got
1524 elem_typeid = array_typelem;
1526 else if (array_typelem != elem_typeid)
1528 /* otherwise, they better match */
1530 (errcode(ERRCODE_DATATYPE_MISMATCH),
1531 errmsg("argument declared \"anyarray\" is not consistent with argument declared \"anyelement\""),
1532 errdetail("%s versus %s",
1533 format_type_be(array_typeid),
1534 format_type_be(elem_typeid))));
1537 else if (!OidIsValid(elem_typeid))
1541 array_typeid = ANYARRAYOID;
1542 elem_typeid = ANYELEMENTOID;
1546 /* Only way to get here is if all the generic args are UNKNOWN */
1548 (errcode(ERRCODE_DATATYPE_MISMATCH),
1549 errmsg("could not determine polymorphic type because input has type \"unknown\"")));
1553 if (have_anynonarray && elem_typeid != ANYELEMENTOID)
1555 /* require the element type to not be an array */
1556 if (type_is_array(elem_typeid))
1558 (errcode(ERRCODE_DATATYPE_MISMATCH),
1559 errmsg("type matched to anynonarray is an array type: %s",
1560 format_type_be(elem_typeid))));
1563 if (have_anyenum && elem_typeid != ANYELEMENTOID)
1565 /* require the element type to be an enum */
1566 if (!type_is_enum(elem_typeid))
1568 (errcode(ERRCODE_DATATYPE_MISMATCH),
1569 errmsg("type matched to anyenum is not an enum type: %s",
1570 format_type_be(elem_typeid))));
1574 * If we had any unknown inputs, re-scan to assign correct types
1578 for (j = 0; j < nargs; j++)
1580 Oid decl_type = declared_arg_types[j];
1581 Oid actual_type = actual_arg_types[j];
1583 if (actual_type != UNKNOWNOID)
1586 if (decl_type == ANYELEMENTOID ||
1587 decl_type == ANYNONARRAYOID ||
1588 decl_type == ANYENUMOID)
1589 declared_arg_types[j] = elem_typeid;
1590 else if (decl_type == ANYARRAYOID)
1592 if (!OidIsValid(array_typeid))
1594 array_typeid = get_array_type(elem_typeid);
1595 if (!OidIsValid(array_typeid))
1597 (errcode(ERRCODE_UNDEFINED_OBJECT),
1598 errmsg("could not find array type for data type %s",
1599 format_type_be(elem_typeid))));
1601 declared_arg_types[j] = array_typeid;
1606 /* if we return ANYARRAY use the appropriate argument type */
1607 if (rettype == ANYARRAYOID)
1609 if (!OidIsValid(array_typeid))
1611 array_typeid = get_array_type(elem_typeid);
1612 if (!OidIsValid(array_typeid))
1614 (errcode(ERRCODE_UNDEFINED_OBJECT),
1615 errmsg("could not find array type for data type %s",
1616 format_type_be(elem_typeid))));
1618 return array_typeid;
1621 /* if we return ANYELEMENT use the appropriate argument type */
1622 if (rettype == ANYELEMENTOID ||
1623 rettype == ANYNONARRAYOID ||
1624 rettype == ANYENUMOID)
1627 /* we don't return a generic type; send back the original return type */
1632 * resolve_generic_type()
1633 * Deduce an individual actual datatype on the assumption that
1634 * the rules for polymorphic types are being followed.
1636 * declared_type is the declared datatype we want to resolve.
1637 * context_actual_type is the actual input datatype to some argument
1638 * that has declared datatype context_declared_type.
1640 * If declared_type isn't polymorphic, we just return it. Otherwise,
1641 * context_declared_type must be polymorphic, and we deduce the correct
1642 * return type based on the relationship of the two polymorphic types.
1645 resolve_generic_type(Oid declared_type,
1646 Oid context_actual_type,
1647 Oid context_declared_type)
1649 if (declared_type == ANYARRAYOID)
1651 if (context_declared_type == ANYARRAYOID)
1653 /* Use actual type, but it must be an array */
1654 Oid array_typelem = get_element_type(context_actual_type);
1656 if (!OidIsValid(array_typelem))
1658 (errcode(ERRCODE_DATATYPE_MISMATCH),
1659 errmsg("argument declared \"anyarray\" is not an array but type %s",
1660 format_type_be(context_actual_type))));
1661 return context_actual_type;
1663 else if (context_declared_type == ANYELEMENTOID ||
1664 context_declared_type == ANYNONARRAYOID ||
1665 context_declared_type == ANYENUMOID)
1667 /* Use the array type corresponding to actual type */
1668 Oid array_typeid = get_array_type(context_actual_type);
1670 if (!OidIsValid(array_typeid))
1672 (errcode(ERRCODE_UNDEFINED_OBJECT),
1673 errmsg("could not find array type for data type %s",
1674 format_type_be(context_actual_type))));
1675 return array_typeid;
1678 else if (declared_type == ANYELEMENTOID ||
1679 declared_type == ANYNONARRAYOID ||
1680 declared_type == ANYENUMOID)
1682 if (context_declared_type == ANYARRAYOID)
1684 /* Use the element type corresponding to actual type */
1685 Oid array_typelem = get_element_type(context_actual_type);
1687 if (!OidIsValid(array_typelem))
1689 (errcode(ERRCODE_DATATYPE_MISMATCH),
1690 errmsg("argument declared \"anyarray\" is not an array but type %s",
1691 format_type_be(context_actual_type))));
1692 return array_typelem;
1694 else if (context_declared_type == ANYELEMENTOID ||
1695 context_declared_type == ANYNONARRAYOID ||
1696 context_declared_type == ANYENUMOID)
1698 /* Use the actual type; it doesn't matter if array or not */
1699 return context_actual_type;
1704 /* declared_type isn't polymorphic, so return it as-is */
1705 return declared_type;
1707 /* If we get here, declared_type is polymorphic and context isn't */
1708 /* NB: this is a calling-code logic error, not a user error */
1709 elog(ERROR, "could not determine polymorphic type because context isn't polymorphic");
1710 return InvalidOid; /* keep compiler quiet */
1715 * Assign a category to the specified type OID.
1717 * NB: this must not return TYPCATEGORY_INVALID.
1720 TypeCategory(Oid type)
1723 bool typispreferred;
1725 get_type_category_preferred(type, &typcategory, &typispreferred);
1726 Assert(typcategory != TYPCATEGORY_INVALID);
1727 return (TYPCATEGORY) typcategory;
1731 /* IsPreferredType()
1732 * Check if this type is a preferred type for the given category.
1734 * If category is TYPCATEGORY_INVALID, then we'll return TRUE for preferred
1735 * types of any category; otherwise, only for preferred types of that
1739 IsPreferredType(TYPCATEGORY category, Oid type)
1742 bool typispreferred;
1744 get_type_category_preferred(type, &typcategory, &typispreferred);
1745 if (category == typcategory || category == TYPCATEGORY_INVALID)
1746 return typispreferred;
1752 /* IsBinaryCoercible()
1753 * Check if srctype is binary-coercible to targettype.
1755 * This notion allows us to cheat and directly exchange values without
1756 * going through the trouble of calling a conversion function. Note that
1757 * in general, this should only be an implementation shortcut. Before 7.4,
1758 * this was also used as a heuristic for resolving overloaded functions and
1759 * operators, but that's basically a bad idea.
1761 * As of 7.3, binary coercibility isn't hardwired into the code anymore.
1762 * We consider two types binary-coercible if there is an implicitly
1763 * invokable, no-function-needed pg_cast entry. Also, a domain is always
1764 * binary-coercible to its base type, though *not* vice versa (in the other
1765 * direction, one must apply domain constraint checks before accepting the
1766 * value as legitimate). We also need to special-case various polymorphic
1769 * This function replaces IsBinaryCompatible(), which was an inherently
1770 * symmetric test. Since the pg_cast entries aren't necessarily symmetric,
1771 * the order of the operands is now significant.
1774 IsBinaryCoercible(Oid srctype, Oid targettype)
1777 Form_pg_cast castForm;
1780 /* Fast path if same type */
1781 if (srctype == targettype)
1784 /* If srctype is a domain, reduce to its base type */
1785 if (OidIsValid(srctype))
1786 srctype = getBaseType(srctype);
1788 /* Somewhat-fast path for domain -> base type case */
1789 if (srctype == targettype)
1792 /* Also accept any array type as coercible to ANYARRAY */
1793 if (targettype == ANYARRAYOID)
1794 if (type_is_array(srctype))
1797 /* Also accept any non-array type as coercible to ANYNONARRAY */
1798 if (targettype == ANYNONARRAYOID)
1799 if (!type_is_array(srctype))
1802 /* Also accept any enum type as coercible to ANYENUM */
1803 if (targettype == ANYENUMOID)
1804 if (type_is_enum(srctype))
1807 /* Also accept any composite type as coercible to RECORD */
1808 if (targettype == RECORDOID)
1809 if (ISCOMPLEX(srctype))
1812 /* Also accept any composite array type as coercible to RECORD[] */
1813 if (targettype == RECORDARRAYOID)
1814 if (is_complex_array(srctype))
1817 /* Else look in pg_cast */
1818 tuple = SearchSysCache2(CASTSOURCETARGET,
1819 ObjectIdGetDatum(srctype),
1820 ObjectIdGetDatum(targettype));
1821 if (!HeapTupleIsValid(tuple))
1822 return false; /* no cast */
1823 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1825 result = (castForm->castmethod == COERCION_METHOD_BINARY &&
1826 castForm->castcontext == COERCION_CODE_IMPLICIT);
1828 ReleaseSysCache(tuple);
1835 * find_coercion_pathway
1836 * Look for a coercion pathway between two types.
1838 * Currently, this deals only with scalar-type cases; it does not consider
1839 * polymorphic types nor casts between composite types. (Perhaps fold
1840 * those in someday?)
1842 * ccontext determines the set of available casts.
1844 * The possible result codes are:
1845 * COERCION_PATH_NONE: failed to find any coercion pathway
1846 * *funcid is set to InvalidOid
1847 * COERCION_PATH_FUNC: apply the coercion function returned in *funcid
1848 * COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
1849 * *funcid is set to InvalidOid
1850 * COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
1851 * *funcid is set to the element cast function, or InvalidOid
1852 * if the array elements are binary-compatible
1853 * COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
1854 * *funcid is set to InvalidOid
1856 * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
1857 * needed to do the coercion; if the target is a domain then we may need to
1858 * apply domain constraint checking. If you want to check for a zero-effort
1859 * conversion then use IsBinaryCoercible().
1862 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
1863 CoercionContext ccontext,
1866 CoercionPathType result = COERCION_PATH_NONE;
1869 *funcid = InvalidOid;
1871 /* Perhaps the types are domains; if so, look at their base types */
1872 if (OidIsValid(sourceTypeId))
1873 sourceTypeId = getBaseType(sourceTypeId);
1874 if (OidIsValid(targetTypeId))
1875 targetTypeId = getBaseType(targetTypeId);
1877 /* Domains are always coercible to and from their base type */
1878 if (sourceTypeId == targetTypeId)
1879 return COERCION_PATH_RELABELTYPE;
1881 /* Look in pg_cast */
1882 tuple = SearchSysCache2(CASTSOURCETARGET,
1883 ObjectIdGetDatum(sourceTypeId),
1884 ObjectIdGetDatum(targetTypeId));
1886 if (HeapTupleIsValid(tuple))
1888 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1889 CoercionContext castcontext;
1891 /* convert char value for castcontext to CoercionContext enum */
1892 switch (castForm->castcontext)
1894 case COERCION_CODE_IMPLICIT:
1895 castcontext = COERCION_IMPLICIT;
1897 case COERCION_CODE_ASSIGNMENT:
1898 castcontext = COERCION_ASSIGNMENT;
1900 case COERCION_CODE_EXPLICIT:
1901 castcontext = COERCION_EXPLICIT;
1904 elog(ERROR, "unrecognized castcontext: %d",
1905 (int) castForm->castcontext);
1906 castcontext = 0; /* keep compiler quiet */
1910 /* Rely on ordering of enum for correct behavior here */
1911 if (ccontext >= castcontext)
1913 switch (castForm->castmethod)
1915 case COERCION_METHOD_FUNCTION:
1916 result = COERCION_PATH_FUNC;
1917 *funcid = castForm->castfunc;
1919 case COERCION_METHOD_INOUT:
1920 result = COERCION_PATH_COERCEVIAIO;
1922 case COERCION_METHOD_BINARY:
1923 result = COERCION_PATH_RELABELTYPE;
1926 elog(ERROR, "unrecognized castmethod: %d",
1927 (int) castForm->castmethod);
1932 ReleaseSysCache(tuple);
1937 * If there's no pg_cast entry, perhaps we are dealing with a pair of
1938 * array types. If so, and if the element types have a suitable cast,
1939 * report that we can coerce with an ArrayCoerceExpr.
1941 * Note that the source type can be a domain over array, but not the
1942 * target, because ArrayCoerceExpr won't check domain constraints.
1944 * Hack: disallow coercions to oidvector and int2vector, which
1945 * otherwise tend to capture coercions that should go to "real" array
1946 * types. We want those types to be considered "real" arrays for many
1947 * purposes, but not this one. (Also, ArrayCoerceExpr isn't
1948 * guaranteed to produce an output that meets the restrictions of
1949 * these datatypes, such as being 1-dimensional.)
1951 if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
1956 if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
1957 (sourceElem = get_base_element_type(sourceTypeId)) != InvalidOid)
1959 CoercionPathType elempathtype;
1962 elempathtype = find_coercion_pathway(targetElem,
1966 if (elempathtype != COERCION_PATH_NONE &&
1967 elempathtype != COERCION_PATH_ARRAYCOERCE)
1969 *funcid = elemfuncid;
1970 if (elempathtype == COERCION_PATH_COERCEVIAIO)
1971 result = COERCION_PATH_COERCEVIAIO;
1973 result = COERCION_PATH_ARRAYCOERCE;
1979 * If we still haven't found a possibility, consider automatic casting
1980 * using I/O functions. We allow assignment casts to string types and
1981 * explicit casts from string types to be handled this way. (The
1982 * CoerceViaIO mechanism is a lot more general than that, but this is
1983 * all we want to allow in the absence of a pg_cast entry.) It would
1984 * probably be better to insist on explicit casts in both directions,
1985 * but this is a compromise to preserve something of the pre-8.3
1986 * behavior that many types had implicit (yipes!) casts to text.
1988 if (result == COERCION_PATH_NONE)
1990 if (ccontext >= COERCION_ASSIGNMENT &&
1991 TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
1992 result = COERCION_PATH_COERCEVIAIO;
1993 else if (ccontext >= COERCION_EXPLICIT &&
1994 TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
1995 result = COERCION_PATH_COERCEVIAIO;
2004 * find_typmod_coercion_function -- does the given type need length coercion?
2006 * If the target type possesses a pg_cast function from itself to itself,
2007 * it must need length coercion.
2009 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
2011 * If the given type is a varlena array type, we do not look for a coercion
2012 * function associated directly with the array type, but instead look for
2013 * one associated with the element type. An ArrayCoerceExpr node must be
2014 * used to apply such a function.
2016 * We use the same result enum as find_coercion_pathway, but the only possible
2018 * COERCION_PATH_NONE: no length coercion needed
2019 * COERCION_PATH_FUNC: apply the function returned in *funcid
2020 * COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
2023 find_typmod_coercion_function(Oid typeId,
2026 CoercionPathType result;
2028 Form_pg_type typeForm;
2031 *funcid = InvalidOid;
2032 result = COERCION_PATH_FUNC;
2034 targetType = typeidType(typeId);
2035 typeForm = (Form_pg_type) GETSTRUCT(targetType);
2037 /* Check for a varlena array type */
2038 if (typeForm->typelem != InvalidOid && typeForm->typlen == -1)
2040 /* Yes, switch our attention to the element type */
2041 typeId = typeForm->typelem;
2042 result = COERCION_PATH_ARRAYCOERCE;
2044 ReleaseSysCache(targetType);
2046 /* Look in pg_cast */
2047 tuple = SearchSysCache2(CASTSOURCETARGET,
2048 ObjectIdGetDatum(typeId),
2049 ObjectIdGetDatum(typeId));
2051 if (HeapTupleIsValid(tuple))
2053 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2055 *funcid = castForm->castfunc;
2056 ReleaseSysCache(tuple);
2059 if (!OidIsValid(*funcid))
2060 result = COERCION_PATH_NONE;
2067 * Is this type an array of composite?
2069 * Note: this will not return true for record[]; check for RECORDARRAYOID
2070 * separately if needed.
2073 is_complex_array(Oid typid)
2075 Oid elemtype = get_element_type(typid);
2077 return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));
2082 * Check whether reltypeId is the row type of a typed table of type
2083 * reloftypeId. (This is conceptually similar to the subtype
2084 * relationship checked by typeInheritsFrom().)
2087 typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
2089 Oid relid = typeidTypeRelid(reltypeId);
2090 bool result = false;
2095 Form_pg_class reltup;
2097 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2098 if (!HeapTupleIsValid(tp))
2099 elog(ERROR, "cache lookup failed for relation %u", relid);
2101 reltup = (Form_pg_class) GETSTRUCT(tp);
2102 if (reltup->reloftype == reloftypeId)
2105 ReleaseSysCache(tp);