]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_coerce.c
When a GUC string variable is not set, print the empty string (in SHOW etc.),
[postgresql] / src / backend / parser / parse_coerce.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_coerce.c
4  *              handle type coercions/conversions for parser
5  *
6  * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/parser/parse_coerce.c,v 2.142 2006/07/26 00:34:48 momjian Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include "catalog/pg_cast.h"
18 #include "catalog/pg_proc.h"
19 #include "catalog/pg_type.h"
20 #include "nodes/makefuncs.h"
21 #include "optimizer/clauses.h"
22 #include "parser/parse_coerce.h"
23 #include "parser/parse_expr.h"
24 #include "parser/parse_func.h"
25 #include "parser/parse_relation.h"
26 #include "parser/parse_type.h"
27 #include "utils/builtins.h"
28 #include "utils/fmgroids.h"
29 #include "utils/lsyscache.h"
30 #include "utils/syscache.h"
31 #include "utils/typcache.h"
32
33
34 static Node *coerce_type_typmod(Node *node,
35                                    Oid targetTypeId, int32 targetTypMod,
36                                    CoercionForm cformat, bool isExplicit,
37                                    bool hideInputCoercion);
38 static void hide_coercion_node(Node *node);
39 static Node *build_coercion_expression(Node *node, Oid funcId,
40                                                   Oid targetTypeId, int32 targetTypMod,
41                                                   CoercionForm cformat, bool isExplicit);
42 static Node *coerce_record_to_complex(ParseState *pstate, Node *node,
43                                                  Oid targetTypeId,
44                                                  CoercionContext ccontext,
45                                                  CoercionForm cformat);
46
47
48 /*
49  * coerce_to_target_type()
50  *              Convert an expression to a target type and typmod.
51  *
52  * This is the general-purpose entry point for arbitrary type coercion
53  * operations.  Direct use of the component operations can_coerce_type,
54  * coerce_type, and coerce_type_typmod should be restricted to special
55  * cases (eg, when the conversion is expected to succeed).
56  *
57  * Returns the possibly-transformed expression tree, or NULL if the type
58  * conversion is not possible.  (We do this, rather than ereport'ing directly,
59  * so that callers can generate custom error messages indicating context.)
60  *
61  * pstate - parse state (can be NULL, see coerce_type)
62  * expr - input expression tree (already transformed by transformExpr)
63  * exprtype - result type of expr
64  * targettype - desired result type
65  * targettypmod - desired result typmod
66  * ccontext, cformat - context indicators to control coercions
67  */
68 Node *
69 coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype,
70                                           Oid targettype, int32 targettypmod,
71                                           CoercionContext ccontext,
72                                           CoercionForm cformat)
73 {
74         Node       *result;
75
76         if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
77                 return NULL;
78
79         result = coerce_type(pstate, expr, exprtype,
80                                                  targettype, targettypmod,
81                                                  ccontext, cformat);
82
83         /*
84          * If the target is a fixed-length type, it may need a length coercion as
85          * well as a type coercion.  If we find ourselves adding both, force the
86          * inner coercion node to implicit display form.
87          */
88         result = coerce_type_typmod(result,
89                                                                 targettype, targettypmod,
90                                                                 cformat,
91                                                                 (cformat != COERCE_IMPLICIT_CAST),
92                                                                 (result != expr && !IsA(result, Const)));
93
94         return result;
95 }
96
97
98 /*
99  * coerce_type()
100  *              Convert an expression to a different type.
101  *
102  * The caller should already have determined that the coercion is possible;
103  * see can_coerce_type.
104  *
105  * Normally, no coercion to a typmod (length) is performed here.  The caller
106  * must call coerce_type_typmod as well, if a typmod constraint is wanted.
107  * (But if the target type is a domain, it may internally contain a
108  * typmod constraint, which will be applied inside coerce_to_domain.)
109  * In some cases pg_cast specifies a type coercion function that also
110  * applies length conversion, and in those cases only, the result will
111  * already be properly coerced to the specified typmod.
112  *
113  * pstate is only used in the case that we are able to resolve the type of
114  * a previously UNKNOWN Param.  It is okay to pass pstate = NULL if the
115  * caller does not want type information updated for Params.
116  */
117 Node *
118 coerce_type(ParseState *pstate, Node *node,
119                         Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
120                         CoercionContext ccontext, CoercionForm cformat)
121 {
122         Node       *result;
123         Oid                     funcId;
124
125         if (targetTypeId == inputTypeId ||
126                 node == NULL)
127         {
128                 /* no conversion needed */
129                 return node;
130         }
131         if (targetTypeId == ANYOID ||
132                 targetTypeId == ANYARRAYOID ||
133                 targetTypeId == ANYELEMENTOID)
134         {
135                 /* assume can_coerce_type verified that implicit coercion is okay */
136                 /* NB: we do NOT want a RelabelType here */
137                 return node;
138         }
139         if (inputTypeId == UNKNOWNOID && IsA(node, Const))
140         {
141                 /*
142                  * Input is a string constant with previously undetermined type. Apply
143                  * the target type's typinput function to it to produce a constant of
144                  * the target type.
145                  *
146                  * NOTE: this case cannot be folded together with the other
147                  * constant-input case, since the typinput function does not
148                  * necessarily behave the same as a type conversion function. For
149                  * example, int4's typinput function will reject "1.2", whereas
150                  * float-to-int type conversion will round to integer.
151                  *
152                  * XXX if the typinput function is not immutable, we really ought to
153                  * postpone evaluation of the function call until runtime. But there
154                  * is no way to represent a typinput function call as an expression
155                  * tree, because C-string values are not Datums. (XXX This *is*
156                  * possible as of 7.3, do we want to do it?)
157                  */
158                 Const      *con = (Const *) node;
159                 Const      *newcon = makeNode(Const);
160                 Oid                     baseTypeId;
161                 int32           baseTypeMod;
162                 Type            targetType;
163
164                 /*
165                  * If the target type is a domain, we want to call its base type's
166                  * input routine, not domain_in().  This is to avoid premature
167                  * failure when the domain applies a typmod: existing input
168                  * routines follow implicit-coercion semantics for length checks,
169                  * which is not always what we want here.  The needed check will
170                  * be applied properly inside coerce_to_domain().
171                  */
172                 baseTypeMod = -1;
173                 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
174
175                 targetType = typeidType(baseTypeId);
176
177                 newcon->consttype = baseTypeId;
178                 newcon->constlen = typeLen(targetType);
179                 newcon->constbyval = typeByVal(targetType);
180                 newcon->constisnull = con->constisnull;
181
182                 /*
183                  * We pass typmod -1 to the input routine, primarily because
184                  * existing input routines follow implicit-coercion semantics for
185                  * length checks, which is not always what we want here. Any
186                  * length constraint will be applied later by our caller.
187                  *
188                  * We assume here that UNKNOWN's internal representation is the
189                  * same as CSTRING.
190                  */
191                 if (!con->constisnull)
192                         newcon->constvalue = stringTypeDatum(targetType,
193                                                                                         DatumGetCString(con->constvalue),
194                                                                                                  -1);
195                 else
196                         newcon->constvalue = stringTypeDatum(targetType, NULL, -1);
197
198                 result = (Node *) newcon;
199
200                 /* If target is a domain, apply constraints. */
201                 if (baseTypeId != targetTypeId)
202                         result = coerce_to_domain(result,
203                                                                           baseTypeId, baseTypeMod,
204                                                                           targetTypeId,
205                                                                           cformat, false, false);
206
207                 ReleaseSysCache(targetType);
208
209                 return result;
210         }
211         if (inputTypeId == UNKNOWNOID && IsA(node, Param) &&
212                 ((Param *) node)->paramkind == PARAM_EXTERN &&
213                 pstate != NULL && pstate->p_variableparams)
214         {
215                 /*
216                  * Input is a Param of previously undetermined type, and we want to
217                  * update our knowledge of the Param's type.  Find the topmost
218                  * ParseState and update the state.
219                  */
220                 Param      *param = (Param *) node;
221                 int                     paramno = param->paramid;
222                 ParseState *toppstate;
223
224                 toppstate = pstate;
225                 while (toppstate->parentParseState != NULL)
226                         toppstate = toppstate->parentParseState;
227
228                 if (paramno <= 0 ||             /* shouldn't happen, but... */
229                         paramno > toppstate->p_numparams)
230                         ereport(ERROR,
231                                         (errcode(ERRCODE_UNDEFINED_PARAMETER),
232                                          errmsg("there is no parameter $%d", paramno)));
233
234                 if (toppstate->p_paramtypes[paramno - 1] == UNKNOWNOID)
235                 {
236                         /* We've successfully resolved the type */
237                         toppstate->p_paramtypes[paramno - 1] = targetTypeId;
238                 }
239                 else if (toppstate->p_paramtypes[paramno - 1] == targetTypeId)
240                 {
241                         /* We previously resolved the type, and it matches */
242                 }
243                 else
244                 {
245                         /* Ooops */
246                         ereport(ERROR,
247                                         (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
248                                          errmsg("inconsistent types deduced for parameter $%d",
249                                                         paramno),
250                                          errdetail("%s versus %s",
251                                                 format_type_be(toppstate->p_paramtypes[paramno - 1]),
252                                                            format_type_be(targetTypeId))));
253                 }
254
255                 param->paramtype = targetTypeId;
256
257                 return (Node *) param;
258         }
259         if (find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
260                                                           &funcId))
261         {
262                 if (OidIsValid(funcId))
263                 {
264                         /*
265                          * Generate an expression tree representing run-time application
266                          * of the conversion function.  If we are dealing with a domain
267                          * target type, the conversion function will yield the base type,
268                          * and we need to extract the correct typmod to use from the
269                          * domain's typtypmod.
270                          */
271                         Oid                     baseTypeId;
272                         int32           baseTypeMod;
273
274                         baseTypeMod = targetTypeMod;
275                         baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
276
277                         result = build_coercion_expression(node, funcId,
278                                                                                            baseTypeId, baseTypeMod,
279                                                                                            cformat,
280                                                                                   (cformat != COERCE_IMPLICIT_CAST));
281
282                         /*
283                          * If domain, coerce to the domain type and relabel with domain
284                          * type ID.  We can skip the internal length-coercion step if the
285                          * selected coercion function was a type-and-length coercion.
286                          */
287                         if (targetTypeId != baseTypeId)
288                                 result = coerce_to_domain(result, baseTypeId, baseTypeMod,
289                                                                                   targetTypeId,
290                                                                                   cformat, true,
291                                                                                   exprIsLengthCoercion(result,
292                                                                                                                            NULL));
293                 }
294                 else
295                 {
296                         /*
297                          * We don't need to do a physical conversion, but we do need to
298                          * attach a RelabelType node so that the expression will be seen
299                          * to have the intended type when inspected by higher-level code.
300                          *
301                          * Also, domains may have value restrictions beyond the base type
302                          * that must be accounted for.  If the destination is a domain
303                          * then we won't need a RelabelType node.
304                          */
305                         result = coerce_to_domain(node, InvalidOid, -1, targetTypeId,
306                                                                           cformat, false, false);
307                         if (result == node)
308                         {
309                                 /*
310                                  * XXX could we label result with exprTypmod(node) instead of
311                                  * default -1 typmod, to save a possible length-coercion
312                                  * later? Would work if both types have same interpretation of
313                                  * typmod, which is likely but not certain.
314                                  */
315                                 result = (Node *) makeRelabelType((Expr *) result,
316                                                                                                   targetTypeId, -1,
317                                                                                                   cformat);
318                         }
319                 }
320                 return result;
321         }
322         if (inputTypeId == RECORDOID &&
323                 ISCOMPLEX(targetTypeId))
324         {
325                 /* Coerce a RECORD to a specific complex type */
326                 return coerce_record_to_complex(pstate, node, targetTypeId,
327                                                                                 ccontext, cformat);
328         }
329         if (targetTypeId == RECORDOID &&
330                 ISCOMPLEX(inputTypeId))
331         {
332                 /* Coerce a specific complex type to RECORD */
333                 /* NB: we do NOT want a RelabelType here */
334                 return node;
335         }
336         if (typeInheritsFrom(inputTypeId, targetTypeId))
337         {
338                 /*
339                  * Input class type is a subclass of target, so generate an
340                  * appropriate runtime conversion (removing unneeded columns and
341                  * possibly rearranging the ones that are wanted).
342                  */
343                 ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
344
345                 r->arg = (Expr *) node;
346                 r->resulttype = targetTypeId;
347                 r->convertformat = cformat;
348                 return (Node *) r;
349         }
350         /* If we get here, caller blew it */
351         elog(ERROR, "failed to find conversion function from %s to %s",
352                  format_type_be(inputTypeId), format_type_be(targetTypeId));
353         return NULL;                            /* keep compiler quiet */
354 }
355
356
357 /*
358  * can_coerce_type()
359  *              Can input_typeids be coerced to target_typeids?
360  *
361  * We must be told the context (CAST construct, assignment, implicit coercion)
362  * as this determines the set of available casts.
363  */
364 bool
365 can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids,
366                                 CoercionContext ccontext)
367 {
368         bool            have_generics = false;
369         int                     i;
370
371         /* run through argument list... */
372         for (i = 0; i < nargs; i++)
373         {
374                 Oid                     inputTypeId = input_typeids[i];
375                 Oid                     targetTypeId = target_typeids[i];
376                 Oid                     funcId;
377
378                 /* no problem if same type */
379                 if (inputTypeId == targetTypeId)
380                         continue;
381
382                 /* accept if target is ANY */
383                 if (targetTypeId == ANYOID)
384                         continue;
385
386                 /* accept if target is ANYARRAY or ANYELEMENT, for now */
387                 if (targetTypeId == ANYARRAYOID ||
388                         targetTypeId == ANYELEMENTOID)
389                 {
390                         have_generics = true;           /* do more checking later */
391                         continue;
392                 }
393
394                 /*
395                  * If input is an untyped string constant, assume we can convert it to
396                  * anything.
397                  */
398                 if (inputTypeId == UNKNOWNOID)
399                         continue;
400
401                 /*
402                  * If pg_cast shows that we can coerce, accept.  This test now covers
403                  * both binary-compatible and coercion-function cases.
404                  */
405                 if (find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
406                                                                   &funcId))
407                         continue;
408
409                 /*
410                  * If input is RECORD and target is a composite type, assume we can
411                  * coerce (may need tighter checking here)
412                  */
413                 if (inputTypeId == RECORDOID &&
414                         ISCOMPLEX(targetTypeId))
415                         continue;
416
417                 /*
418                  * If input is a composite type and target is RECORD, accept
419                  */
420                 if (targetTypeId == RECORDOID &&
421                         ISCOMPLEX(inputTypeId))
422                         continue;
423
424                 /*
425                  * If input is a class type that inherits from target, accept
426                  */
427                 if (typeInheritsFrom(inputTypeId, targetTypeId))
428                         continue;
429
430                 /*
431                  * Else, cannot coerce at this argument position
432                  */
433                 return false;
434         }
435
436         /* If we found any generic argument types, cross-check them */
437         if (have_generics)
438         {
439                 if (!check_generic_type_consistency(input_typeids, target_typeids,
440                                                                                         nargs))
441                         return false;
442         }
443
444         return true;
445 }
446
447
448 /*
449  * Create an expression tree to represent coercion to a domain type.
450  *
451  * 'arg': input expression
452  * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
453  *              has not bothered to look this up)
454  * 'baseTypeMod': base type typmod of domain, if known (pass -1 if caller
455  *              has not bothered to look this up)
456  * 'typeId': target type to coerce to
457  * 'cformat': coercion format
458  * 'hideInputCoercion': if true, hide the input coercion under this one.
459  * 'lengthCoercionDone': if true, caller already accounted for length,
460  *              ie the input is already of baseTypMod as well as baseTypeId.
461  *
462  * If the target type isn't a domain, the given 'arg' is returned as-is.
463  */
464 Node *
465 coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId,
466                                  CoercionForm cformat, bool hideInputCoercion,
467                                  bool lengthCoercionDone)
468 {
469         CoerceToDomain *result;
470
471         /* Get the base type if it hasn't been supplied */
472         if (baseTypeId == InvalidOid)
473                 baseTypeId = getBaseTypeAndTypmod(typeId, &baseTypeMod);
474
475         /* If it isn't a domain, return the node as it was passed in */
476         if (baseTypeId == typeId)
477                 return arg;
478
479         /* Suppress display of nested coercion steps */
480         if (hideInputCoercion)
481                 hide_coercion_node(arg);
482
483         /*
484          * If the domain applies a typmod to its base type, build the appropriate
485          * coercion step.  Mark it implicit for display purposes, because we don't
486          * want it shown separately by ruleutils.c; but the isExplicit flag passed
487          * to the conversion function depends on the manner in which the domain
488          * coercion is invoked, so that the semantics of implicit and explicit
489          * coercion differ.  (Is that really the behavior we want?)
490          *
491          * NOTE: because we apply this as part of the fixed expression structure,
492          * ALTER DOMAIN cannot alter the typtypmod.  But it's unclear that that
493          * would be safe to do anyway, without lots of knowledge about what the
494          * base type thinks the typmod means.
495          */
496         if (!lengthCoercionDone)
497         {
498                 if (baseTypeMod >= 0)
499                         arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
500                                                                          COERCE_IMPLICIT_CAST,
501                                                                          (cformat != COERCE_IMPLICIT_CAST),
502                                                                          false);
503         }
504
505         /*
506          * Now build the domain coercion node.  This represents run-time checking
507          * of any constraints currently attached to the domain.  This also ensures
508          * that the expression is properly labeled as to result type.
509          */
510         result = makeNode(CoerceToDomain);
511         result->arg = (Expr *) arg;
512         result->resulttype = typeId;
513         result->resulttypmod = -1;      /* currently, always -1 for domains */
514         result->coercionformat = cformat;
515
516         return (Node *) result;
517 }
518
519
520 /*
521  * coerce_type_typmod()
522  *              Force a value to a particular typmod, if meaningful and possible.
523  *
524  * This is applied to values that are going to be stored in a relation
525  * (where we have an atttypmod for the column) as well as values being
526  * explicitly CASTed (where the typmod comes from the target type spec).
527  *
528  * The caller must have already ensured that the value is of the correct
529  * type, typically by applying coerce_type.
530  *
531  * cformat determines the display properties of the generated node (if any),
532  * while isExplicit may affect semantics.  If hideInputCoercion is true
533  * *and* we generate a node, the input node is forced to IMPLICIT display
534  * form, so that only the typmod coercion node will be visible when
535  * displaying the expression.
536  *
537  * NOTE: this does not need to work on domain types, because any typmod
538  * coercion for a domain is considered to be part of the type coercion
539  * needed to produce the domain value in the first place.  So, no getBaseType.
540  */
541 static Node *
542 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
543                                    CoercionForm cformat, bool isExplicit,
544                                    bool hideInputCoercion)
545 {
546         Oid                     funcId;
547
548         /*
549          * A negative typmod is assumed to mean that no coercion is wanted. Also,
550          * skip coercion if already done.
551          */
552         if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
553                 return node;
554
555         funcId = find_typmod_coercion_function(targetTypeId);
556
557         if (OidIsValid(funcId))
558         {
559                 /* Suppress display of nested coercion steps */
560                 if (hideInputCoercion)
561                         hide_coercion_node(node);
562
563                 node = build_coercion_expression(node, funcId,
564                                                                                  targetTypeId, targetTypMod,
565                                                                                  cformat, isExplicit);
566         }
567
568         return node;
569 }
570
571 /*
572  * Mark a coercion node as IMPLICIT so it will never be displayed by
573  * ruleutils.c.  We use this when we generate a nest of coercion nodes
574  * to implement what is logically one conversion; the inner nodes are
575  * forced to IMPLICIT_CAST format.      This does not change their semantics,
576  * only display behavior.
577  *
578  * It is caller error to call this on something that doesn't have a
579  * CoercionForm field.
580  */
581 static void
582 hide_coercion_node(Node *node)
583 {
584         if (IsA(node, FuncExpr))
585                 ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
586         else if (IsA(node, RelabelType))
587                 ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
588         else if (IsA(node, ConvertRowtypeExpr))
589                 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
590         else if (IsA(node, RowExpr))
591                 ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
592         else if (IsA(node, CoerceToDomain))
593                 ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
594         else
595                 elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
596 }
597
598 /*
599  * build_coercion_expression()
600  *              Construct a function-call expression for applying a pg_cast entry.
601  *
602  * This is used for both type-coercion and length-coercion functions,
603  * since there is no difference in terms of the calling convention.
604  */
605 static Node *
606 build_coercion_expression(Node *node, Oid funcId,
607                                                   Oid targetTypeId, int32 targetTypMod,
608                                                   CoercionForm cformat, bool isExplicit)
609 {
610         HeapTuple       tp;
611         Form_pg_proc procstruct;
612         int                     nargs;
613         List       *args;
614         Const      *cons;
615
616         tp = SearchSysCache(PROCOID,
617                                                 ObjectIdGetDatum(funcId),
618                                                 0, 0, 0);
619         if (!HeapTupleIsValid(tp))
620                 elog(ERROR, "cache lookup failed for function %u", funcId);
621         procstruct = (Form_pg_proc) GETSTRUCT(tp);
622
623         /*
624          * Asserts essentially check that function is a legal coercion function.
625          * We can't make the seemingly obvious tests on prorettype and
626          * proargtypes[0], because of various binary-compatibility cases.
627          */
628         /* Assert(targetTypeId == procstruct->prorettype); */
629         Assert(!procstruct->proretset);
630         Assert(!procstruct->proisagg);
631         nargs = procstruct->pronargs;
632         Assert(nargs >= 1 && nargs <= 3);
633         /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
634         Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
635         Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
636
637         ReleaseSysCache(tp);
638
639         args = list_make1(node);
640
641         if (nargs >= 2)
642         {
643                 /* Pass target typmod as an int4 constant */
644                 cons = makeConst(INT4OID,
645                                                  sizeof(int32),
646                                                  Int32GetDatum(targetTypMod),
647                                                  false,
648                                                  true);
649
650                 args = lappend(args, cons);
651         }
652
653         if (nargs == 3)
654         {
655                 /* Pass it a boolean isExplicit parameter, too */
656                 cons = makeConst(BOOLOID,
657                                                  sizeof(bool),
658                                                  BoolGetDatum(isExplicit),
659                                                  false,
660                                                  true);
661
662                 args = lappend(args, cons);
663         }
664
665         return (Node *) makeFuncExpr(funcId, targetTypeId, args, cformat);
666 }
667
668
669 /*
670  * coerce_record_to_complex
671  *              Coerce a RECORD to a specific composite type.
672  *
673  * Currently we only support this for inputs that are RowExprs or whole-row
674  * Vars.
675  */
676 static Node *
677 coerce_record_to_complex(ParseState *pstate, Node *node,
678                                                  Oid targetTypeId,
679                                                  CoercionContext ccontext,
680                                                  CoercionForm cformat)
681 {
682         RowExpr    *rowexpr;
683         TupleDesc       tupdesc;
684         List       *args = NIL;
685         List       *newargs;
686         int                     i;
687         int                     ucolno;
688         ListCell   *arg;
689
690         if (node && IsA(node, RowExpr))
691         {
692                 /*
693                  * Since the RowExpr must be of type RECORD, we needn't worry about it
694                  * containing any dropped columns.
695                  */
696                 args = ((RowExpr *) node)->args;
697         }
698         else if (node && IsA(node, Var) &&
699                          ((Var *) node)->varattno == InvalidAttrNumber)
700         {
701                 int                     rtindex = ((Var *) node)->varno;
702                 int                     sublevels_up = ((Var *) node)->varlevelsup;
703                 RangeTblEntry *rte;
704
705                 rte = GetRTEByRangeTablePosn(pstate, rtindex, sublevels_up);
706                 expandRTE(rte, rtindex, sublevels_up, false,
707                                   NULL, &args);
708         }
709         else
710                 ereport(ERROR,
711                                 (errcode(ERRCODE_CANNOT_COERCE),
712                                  errmsg("cannot cast type %s to %s",
713                                                 format_type_be(RECORDOID),
714                                                 format_type_be(targetTypeId))));
715
716         tupdesc = lookup_rowtype_tupdesc(targetTypeId, -1);
717         newargs = NIL;
718         ucolno = 1;
719         arg = list_head(args);
720         for (i = 0; i < tupdesc->natts; i++)
721         {
722                 Node       *expr;
723                 Oid                     exprtype;
724
725                 /* Fill in NULLs for dropped columns in rowtype */
726                 if (tupdesc->attrs[i]->attisdropped)
727                 {
728                         /*
729                          * can't use atttypid here, but it doesn't really matter what type
730                          * the Const claims to be.
731                          */
732                         newargs = lappend(newargs, makeNullConst(INT4OID));
733                         continue;
734                 }
735
736                 if (arg == NULL)
737                         ereport(ERROR,
738                                         (errcode(ERRCODE_CANNOT_COERCE),
739                                          errmsg("cannot cast type %s to %s",
740                                                         format_type_be(RECORDOID),
741                                                         format_type_be(targetTypeId)),
742                                          errdetail("Input has too few columns.")));
743                 expr = (Node *) lfirst(arg);
744                 exprtype = exprType(expr);
745
746                 expr = coerce_to_target_type(pstate,
747                                                                          expr, exprtype,
748                                                                          tupdesc->attrs[i]->atttypid,
749                                                                          tupdesc->attrs[i]->atttypmod,
750                                                                          ccontext,
751                                                                          COERCE_IMPLICIT_CAST);
752                 if (expr == NULL)
753                         ereport(ERROR,
754                                         (errcode(ERRCODE_CANNOT_COERCE),
755                                          errmsg("cannot cast type %s to %s",
756                                                         format_type_be(RECORDOID),
757                                                         format_type_be(targetTypeId)),
758                                          errdetail("Cannot cast type %s to %s in column %d.",
759                                                            format_type_be(exprtype),
760                                                            format_type_be(tupdesc->attrs[i]->atttypid),
761                                                            ucolno)));
762                 newargs = lappend(newargs, expr);
763                 ucolno++;
764                 arg = lnext(arg);
765         }
766         if (arg != NULL)
767                 ereport(ERROR,
768                                 (errcode(ERRCODE_CANNOT_COERCE),
769                                  errmsg("cannot cast type %s to %s",
770                                                 format_type_be(RECORDOID),
771                                                 format_type_be(targetTypeId)),
772                                  errdetail("Input has too many columns.")));
773
774         ReleaseTupleDesc(tupdesc);
775
776         rowexpr = makeNode(RowExpr);
777         rowexpr->args = newargs;
778         rowexpr->row_typeid = targetTypeId;
779         rowexpr->row_format = cformat;
780         return (Node *) rowexpr;
781 }
782
783 /* coerce_to_boolean()
784  *              Coerce an argument of a construct that requires boolean input
785  *              (AND, OR, NOT, etc).  Also check that input is not a set.
786  *
787  * Returns the possibly-transformed node tree.
788  *
789  * As with coerce_type, pstate may be NULL if no special unknown-Param
790  * processing is wanted.
791  */
792 Node *
793 coerce_to_boolean(ParseState *pstate, Node *node,
794                                   const char *constructName)
795 {
796         Oid                     inputTypeId = exprType(node);
797
798         if (inputTypeId != BOOLOID)
799         {
800                 node = coerce_to_target_type(pstate, node, inputTypeId,
801                                                                          BOOLOID, -1,
802                                                                          COERCION_ASSIGNMENT,
803                                                                          COERCE_IMPLICIT_CAST);
804                 if (node == NULL)
805                         ereport(ERROR,
806                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
807                         /* translator: first %s is name of a SQL construct, eg WHERE */
808                                    errmsg("argument of %s must be type boolean, not type %s",
809                                                   constructName, format_type_be(inputTypeId))));
810         }
811
812         if (expression_returns_set(node))
813                 ereport(ERROR,
814                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
815                 /* translator: %s is name of a SQL construct, eg WHERE */
816                                  errmsg("argument of %s must not return a set",
817                                                 constructName)));
818
819         return node;
820 }
821
822 /* coerce_to_integer()
823  *              Coerce an argument of a construct that requires integer input
824  *              Also check that input is not a set.
825  *
826  * Returns the possibly-transformed node tree.
827  *
828  * As with coerce_type, pstate may be NULL if no special unknown-Param
829  * processing is wanted.
830  */
831 Node *
832 coerce_to_integer(ParseState *pstate, Node *node,
833                                   const char *constructName)
834 {
835         Oid                     inputTypeId = exprType(node);
836
837         if (inputTypeId != INT4OID)
838         {
839                 node = coerce_to_target_type(pstate, node, inputTypeId,
840                                                                          INT4OID, -1,
841                                                                          COERCION_ASSIGNMENT,
842                                                                          COERCE_IMPLICIT_CAST);
843                 if (node == NULL)
844                         ereport(ERROR,
845                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
846                         /* translator: first %s is name of a SQL construct, eg LIMIT */
847                                    errmsg("argument of %s must be type integer, not type %s",
848                                                   constructName, format_type_be(inputTypeId))));
849         }
850
851         if (expression_returns_set(node))
852                 ereport(ERROR,
853                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
854                 /* translator: %s is name of a SQL construct, eg LIMIT */
855                                  errmsg("argument of %s must not return a set",
856                                                 constructName)));
857
858         return node;
859 }
860  
861 /* coerce_to_integer64()
862  *              Coerce an argument of a construct that requires integer input
863  *              (LIMIT, OFFSET).  Also check that input is not a set.
864  *
865  * Returns the possibly-transformed node tree.
866  *
867  * As with coerce_type, pstate may be NULL if no special unknown-Param
868  * processing is wanted.
869  */
870 Node *
871 coerce_to_integer64(ParseState *pstate, Node *node,
872                                         const char *constructName)
873 {
874         Oid     inputTypeId = exprType(node);
875
876         if (inputTypeId != INT8OID)
877         {
878                 node = coerce_to_target_type(pstate, node, inputTypeId,
879                                                                          INT8OID, -1, COERCION_ASSIGNMENT,
880                                                                          COERCE_IMPLICIT_CAST);
881                 if (node == NULL)
882                                 ereport(ERROR,
883                                                   (errcode(ERRCODE_DATATYPE_MISMATCH),
884                                           /* translator: first %s is name of a SQL construct, eg LIMIT */
885                                                          errmsg("argument of %s must be type integer, not type %s",
886                                                                         constructName, format_type_be(inputTypeId))));
887         }
888
889         if (expression_returns_set(node))
890                 ereport(ERROR,
891                                   (errcode(ERRCODE_DATATYPE_MISMATCH),
892                   /* translator: %s is name of a SQL construct, eg LIMIT */
893                                            errmsg("argument of %s must not return a set",
894                                                           constructName)));
895
896         return node;
897 }
898   
899
900 /* select_common_type()
901  *              Determine the common supertype of a list of input expression types.
902  *              This is used for determining the output type of CASE and UNION
903  *              constructs.
904  *
905  * typeids is a nonempty list of type OIDs.  Note that earlier items
906  * in the list will be preferred if there is doubt.
907  * 'context' is a phrase to use in the error message if we fail to select
908  * a usable type.
909  */
910 Oid
911 select_common_type(List *typeids, const char *context)
912 {
913         Oid                     ptype;
914         CATEGORY        pcategory;
915         ListCell   *type_item;
916
917         Assert(typeids != NIL);
918         ptype = getBaseType(linitial_oid(typeids));
919         pcategory = TypeCategory(ptype);
920
921         for_each_cell(type_item, lnext(list_head(typeids)))
922         {
923                 Oid                     ntype = getBaseType(lfirst_oid(type_item));
924
925                 /* move on to next one if no new information... */
926                 if ((ntype != InvalidOid) && (ntype != UNKNOWNOID) && (ntype != ptype))
927                 {
928                         if ((ptype == InvalidOid) || ptype == UNKNOWNOID)
929                         {
930                                 /* so far, only nulls so take anything... */
931                                 ptype = ntype;
932                                 pcategory = TypeCategory(ptype);
933                         }
934                         else if (TypeCategory(ntype) != pcategory)
935                         {
936                                 /*
937                                  * both types in different categories? then not much hope...
938                                  */
939                                 ereport(ERROR,
940                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
941
942                                 /*
943                                  * translator: first %s is name of a SQL construct, eg CASE
944                                  */
945                                                  errmsg("%s types %s and %s cannot be matched",
946                                                                 context,
947                                                                 format_type_be(ptype),
948                                                                 format_type_be(ntype))));
949                         }
950                         else if (!IsPreferredType(pcategory, ptype) &&
951                                          can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
952                                          !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
953                         {
954                                 /*
955                                  * take new type if can coerce to it implicitly but not the
956                                  * other way; but if we have a preferred type, stay on it.
957                                  */
958                                 ptype = ntype;
959                                 pcategory = TypeCategory(ptype);
960                         }
961                 }
962         }
963
964         /*
965          * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
966          * then resolve as type TEXT.  This situation comes up with constructs
967          * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
968          * UNION SELECT 'bar'; It might seem desirable to leave the construct's
969          * output type as UNKNOWN, but that really doesn't work, because we'd
970          * probably end up needing a runtime coercion from UNKNOWN to something
971          * else, and we usually won't have it.  We need to coerce the unknown
972          * literals while they are still literals, so a decision has to be made
973          * now.
974          */
975         if (ptype == UNKNOWNOID)
976                 ptype = TEXTOID;
977
978         return ptype;
979 }
980
981 /* coerce_to_common_type()
982  *              Coerce an expression to the given type.
983  *
984  * This is used following select_common_type() to coerce the individual
985  * expressions to the desired type.  'context' is a phrase to use in the
986  * error message if we fail to coerce.
987  *
988  * As with coerce_type, pstate may be NULL if no special unknown-Param
989  * processing is wanted.
990  */
991 Node *
992 coerce_to_common_type(ParseState *pstate, Node *node,
993                                           Oid targetTypeId, const char *context)
994 {
995         Oid                     inputTypeId = exprType(node);
996
997         if (inputTypeId == targetTypeId)
998                 return node;                    /* no work */
999         if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
1000                 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1001                                                    COERCION_IMPLICIT, COERCE_IMPLICIT_CAST);
1002         else
1003                 ereport(ERROR,
1004                                 (errcode(ERRCODE_CANNOT_COERCE),
1005                 /* translator: first %s is name of a SQL construct, eg CASE */
1006                                  errmsg("%s could not convert type %s to %s",
1007                                                 context,
1008                                                 format_type_be(inputTypeId),
1009                                                 format_type_be(targetTypeId))));
1010         return node;
1011 }
1012
1013 /*
1014  * check_generic_type_consistency()
1015  *              Are the actual arguments potentially compatible with a
1016  *              polymorphic function?
1017  *
1018  * The argument consistency rules are:
1019  *
1020  * 1) All arguments declared ANYARRAY must have matching datatypes,
1021  *        and must in fact be varlena arrays.
1022  * 2) All arguments declared ANYELEMENT must have matching datatypes.
1023  * 3) If there are arguments of both ANYELEMENT and ANYARRAY, make sure
1024  *        the actual ANYELEMENT datatype is in fact the element type for
1025  *        the actual ANYARRAY datatype.
1026  *
1027  * If we have UNKNOWN input (ie, an untyped literal) for any ANYELEMENT
1028  * or ANYARRAY argument, assume it is okay.
1029  *
1030  * If an input is of type ANYARRAY (ie, we know it's an array, but not
1031  * what element type), we will accept it as a match to an argument declared
1032  * ANYARRAY, so long as we don't have to determine an element type ---
1033  * that is, so long as there is no use of ANYELEMENT.  This is mostly for
1034  * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
1035  *
1036  * We do not ereport here, but just return FALSE if a rule is violated.
1037  */
1038 bool
1039 check_generic_type_consistency(Oid *actual_arg_types,
1040                                                            Oid *declared_arg_types,
1041                                                            int nargs)
1042 {
1043         int                     j;
1044         Oid                     elem_typeid = InvalidOid;
1045         Oid                     array_typeid = InvalidOid;
1046         Oid                     array_typelem;
1047         bool            have_anyelement = false;
1048
1049         /*
1050          * Loop through the arguments to see if we have any that are ANYARRAY or
1051          * ANYELEMENT. If so, require the actual types to be self-consistent
1052          */
1053         for (j = 0; j < nargs; j++)
1054         {
1055                 Oid                     actual_type = actual_arg_types[j];
1056
1057                 if (declared_arg_types[j] == ANYELEMENTOID)
1058                 {
1059                         have_anyelement = true;
1060                         if (actual_type == UNKNOWNOID)
1061                                 continue;
1062                         if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1063                                 return false;
1064                         elem_typeid = actual_type;
1065                 }
1066                 else if (declared_arg_types[j] == ANYARRAYOID)
1067                 {
1068                         if (actual_type == UNKNOWNOID)
1069                                 continue;
1070                         if (OidIsValid(array_typeid) && actual_type != array_typeid)
1071                                 return false;
1072                         array_typeid = actual_type;
1073                 }
1074         }
1075
1076         /* Get the element type based on the array type, if we have one */
1077         if (OidIsValid(array_typeid))
1078         {
1079                 if (array_typeid == ANYARRAYOID)
1080                 {
1081                         /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1082                         if (have_anyelement)
1083                                 return false;
1084                         return true;
1085                 }
1086
1087                 array_typelem = get_element_type(array_typeid);
1088                 if (!OidIsValid(array_typelem))
1089                         return false;           /* should be an array, but isn't */
1090
1091                 if (!OidIsValid(elem_typeid))
1092                 {
1093                         /*
1094                          * if we don't have an element type yet, use the one we just got
1095                          */
1096                         elem_typeid = array_typelem;
1097                 }
1098                 else if (array_typelem != elem_typeid)
1099                 {
1100                         /* otherwise, they better match */
1101                         return false;
1102                 }
1103         }
1104
1105         /* Looks valid */
1106         return true;
1107 }
1108
1109 /*
1110  * enforce_generic_type_consistency()
1111  *              Make sure a polymorphic function is legally callable, and
1112  *              deduce actual argument and result types.
1113  *
1114  * If ANYARRAY or ANYELEMENT is used for a function's arguments or
1115  * return type, we make sure the actual data types are consistent with
1116  * each other. The argument consistency rules are shown above for
1117  * check_generic_type_consistency().
1118  *
1119  * If we have UNKNOWN input (ie, an untyped literal) for any ANYELEMENT
1120  * or ANYARRAY argument, we attempt to deduce the actual type it should
1121  * have.  If successful, we alter that position of declared_arg_types[]
1122  * so that make_fn_arguments will coerce the literal to the right thing.
1123  *
1124  * Rules are applied to the function's return type (possibly altering it)
1125  * if it is declared ANYARRAY or ANYELEMENT:
1126  *
1127  * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1128  *        argument's actual type as the function's return type.
1129  * 2) If return type is ANYARRAY, no argument is ANYARRAY, but any argument
1130  *        is ANYELEMENT, use the actual type of the argument to determine
1131  *        the function's return type, i.e. the element type's corresponding
1132  *        array type.
1133  * 3) If return type is ANYARRAY, no argument is ANYARRAY or ANYELEMENT,
1134  *        generate an ERROR. This condition is prevented by CREATE FUNCTION
1135  *        and is therefore not expected here.
1136  * 4) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1137  *        argument's actual type as the function's return type.
1138  * 5) If return type is ANYELEMENT, no argument is ANYELEMENT, but any
1139  *        argument is ANYARRAY, use the actual type of the argument to determine
1140  *        the function's return type, i.e. the array type's corresponding
1141  *        element type.
1142  * 6) If return type is ANYELEMENT, no argument is ANYARRAY or ANYELEMENT,
1143  *        generate an ERROR. This condition is prevented by CREATE FUNCTION
1144  *        and is therefore not expected here.
1145  */
1146 Oid
1147 enforce_generic_type_consistency(Oid *actual_arg_types,
1148                                                                  Oid *declared_arg_types,
1149                                                                  int nargs,
1150                                                                  Oid rettype)
1151 {
1152         int                     j;
1153         bool            have_generics = false;
1154         bool            have_unknowns = false;
1155         Oid                     elem_typeid = InvalidOid;
1156         Oid                     array_typeid = InvalidOid;
1157         Oid                     array_typelem;
1158         bool            have_anyelement = (rettype == ANYELEMENTOID);
1159
1160         /*
1161          * Loop through the arguments to see if we have any that are ANYARRAY or
1162          * ANYELEMENT. If so, require the actual types to be self-consistent
1163          */
1164         for (j = 0; j < nargs; j++)
1165         {
1166                 Oid                     actual_type = actual_arg_types[j];
1167
1168                 if (declared_arg_types[j] == ANYELEMENTOID)
1169                 {
1170                         have_generics = have_anyelement = true;
1171                         if (actual_type == UNKNOWNOID)
1172                         {
1173                                 have_unknowns = true;
1174                                 continue;
1175                         }
1176                         if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1177                                 ereport(ERROR,
1178                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1179                                 errmsg("arguments declared \"anyelement\" are not all alike"),
1180                                                  errdetail("%s versus %s",
1181                                                                    format_type_be(elem_typeid),
1182                                                                    format_type_be(actual_type))));
1183                         elem_typeid = actual_type;
1184                 }
1185                 else if (declared_arg_types[j] == ANYARRAYOID)
1186                 {
1187                         have_generics = true;
1188                         if (actual_type == UNKNOWNOID)
1189                         {
1190                                 have_unknowns = true;
1191                                 continue;
1192                         }
1193                         if (OidIsValid(array_typeid) && actual_type != array_typeid)
1194                                 ereport(ERROR,
1195                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1196                                  errmsg("arguments declared \"anyarray\" are not all alike"),
1197                                                  errdetail("%s versus %s",
1198                                                                    format_type_be(array_typeid),
1199                                                                    format_type_be(actual_type))));
1200                         array_typeid = actual_type;
1201                 }
1202         }
1203
1204         /*
1205          * Fast Track: if none of the arguments are ANYARRAY or ANYELEMENT, return
1206          * the unmodified rettype.
1207          */
1208         if (!have_generics)
1209                 return rettype;
1210
1211         /* Get the element type based on the array type, if we have one */
1212         if (OidIsValid(array_typeid))
1213         {
1214                 if (array_typeid == ANYARRAYOID && !have_anyelement)
1215                 {
1216                         /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1217                         array_typelem = InvalidOid;
1218                 }
1219                 else
1220                 {
1221                         array_typelem = get_element_type(array_typeid);
1222                         if (!OidIsValid(array_typelem))
1223                                 ereport(ERROR,
1224                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1225                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1226                                                                 format_type_be(array_typeid))));
1227                 }
1228
1229                 if (!OidIsValid(elem_typeid))
1230                 {
1231                         /*
1232                          * if we don't have an element type yet, use the one we just got
1233                          */
1234                         elem_typeid = array_typelem;
1235                 }
1236                 else if (array_typelem != elem_typeid)
1237                 {
1238                         /* otherwise, they better match */
1239                         ereport(ERROR,
1240                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1241                                          errmsg("argument declared \"anyarray\" is not consistent with argument declared \"anyelement\""),
1242                                          errdetail("%s versus %s",
1243                                                            format_type_be(array_typeid),
1244                                                            format_type_be(elem_typeid))));
1245                 }
1246         }
1247         else if (!OidIsValid(elem_typeid))
1248         {
1249                 /* Only way to get here is if all the generic args are UNKNOWN */
1250                 ereport(ERROR,
1251                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1252                                  errmsg("could not determine anyarray/anyelement type because input has type \"unknown\"")));
1253         }
1254
1255         /*
1256          * If we had any unknown inputs, re-scan to assign correct types
1257          */
1258         if (have_unknowns)
1259         {
1260                 for (j = 0; j < nargs; j++)
1261                 {
1262                         Oid                     actual_type = actual_arg_types[j];
1263
1264                         if (actual_type != UNKNOWNOID)
1265                                 continue;
1266
1267                         if (declared_arg_types[j] == ANYELEMENTOID)
1268                                 declared_arg_types[j] = elem_typeid;
1269                         else if (declared_arg_types[j] == ANYARRAYOID)
1270                         {
1271                                 if (!OidIsValid(array_typeid))
1272                                 {
1273                                         array_typeid = get_array_type(elem_typeid);
1274                                         if (!OidIsValid(array_typeid))
1275                                                 ereport(ERROR,
1276                                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1277                                                  errmsg("could not find array type for data type %s",
1278                                                                 format_type_be(elem_typeid))));
1279                                 }
1280                                 declared_arg_types[j] = array_typeid;
1281                         }
1282                 }
1283         }
1284
1285         /* if we return ANYARRAYOID use the appropriate argument type */
1286         if (rettype == ANYARRAYOID)
1287         {
1288                 if (!OidIsValid(array_typeid))
1289                 {
1290                         array_typeid = get_array_type(elem_typeid);
1291                         if (!OidIsValid(array_typeid))
1292                                 ereport(ERROR,
1293                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1294                                                  errmsg("could not find array type for data type %s",
1295                                                                 format_type_be(elem_typeid))));
1296                 }
1297                 return array_typeid;
1298         }
1299
1300         /* if we return ANYELEMENTOID use the appropriate argument type */
1301         if (rettype == ANYELEMENTOID)
1302                 return elem_typeid;
1303
1304         /* we don't return a generic type; send back the original return type */
1305         return rettype;
1306 }
1307
1308 /*
1309  * resolve_generic_type()
1310  *              Deduce an individual actual datatype on the assumption that
1311  *              the rules for ANYARRAY/ANYELEMENT are being followed.
1312  *
1313  * declared_type is the declared datatype we want to resolve.
1314  * context_actual_type is the actual input datatype to some argument
1315  * that has declared datatype context_declared_type.
1316  *
1317  * If declared_type isn't polymorphic, we just return it.  Otherwise,
1318  * context_declared_type must be polymorphic, and we deduce the correct
1319  * return type based on the relationship of the two polymorphic types.
1320  */
1321 Oid
1322 resolve_generic_type(Oid declared_type,
1323                                          Oid context_actual_type,
1324                                          Oid context_declared_type)
1325 {
1326         if (declared_type == ANYARRAYOID)
1327         {
1328                 if (context_declared_type == ANYARRAYOID)
1329                 {
1330                         /* Use actual type, but it must be an array */
1331                         Oid                     array_typelem = get_element_type(context_actual_type);
1332
1333                         if (!OidIsValid(array_typelem))
1334                                 ereport(ERROR,
1335                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1336                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1337                                                                 format_type_be(context_actual_type))));
1338                         return context_actual_type;
1339                 }
1340                 else if (context_declared_type == ANYELEMENTOID)
1341                 {
1342                         /* Use the array type corresponding to actual type */
1343                         Oid                     array_typeid = get_array_type(context_actual_type);
1344
1345                         if (!OidIsValid(array_typeid))
1346                                 ereport(ERROR,
1347                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1348                                                  errmsg("could not find array type for data type %s",
1349                                                                 format_type_be(context_actual_type))));
1350                         return array_typeid;
1351                 }
1352         }
1353         else if (declared_type == ANYELEMENTOID)
1354         {
1355                 if (context_declared_type == ANYARRAYOID)
1356                 {
1357                         /* Use the element type corresponding to actual type */
1358                         Oid                     array_typelem = get_element_type(context_actual_type);
1359
1360                         if (!OidIsValid(array_typelem))
1361                                 ereport(ERROR,
1362                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1363                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1364                                                                 format_type_be(context_actual_type))));
1365                         return array_typelem;
1366                 }
1367                 else if (context_declared_type == ANYELEMENTOID)
1368                 {
1369                         /* Use the actual type; it doesn't matter if array or not */
1370                         return context_actual_type;
1371                 }
1372         }
1373         else
1374         {
1375                 /* declared_type isn't polymorphic, so return it as-is */
1376                 return declared_type;
1377         }
1378         /* If we get here, declared_type is polymorphic and context isn't */
1379         /* NB: this is a calling-code logic error, not a user error */
1380         elog(ERROR, "could not determine ANYARRAY/ANYELEMENT type because context isn't polymorphic");
1381         return InvalidOid;                      /* keep compiler quiet */
1382 }
1383
1384
1385 /* TypeCategory()
1386  *              Assign a category to the specified type OID.
1387  *
1388  * NB: this must not return INVALID_TYPE.
1389  *
1390  * XXX This should be moved to system catalog lookups
1391  * to allow for better type extensibility.
1392  * - thomas 2001-09-30
1393  */
1394 CATEGORY
1395 TypeCategory(Oid inType)
1396 {
1397         CATEGORY        result;
1398
1399         switch (inType)
1400         {
1401                 case (BOOLOID):
1402                         result = BOOLEAN_TYPE;
1403                         break;
1404
1405                 case (CHAROID):
1406                 case (NAMEOID):
1407                 case (BPCHAROID):
1408                 case (VARCHAROID):
1409                 case (TEXTOID):
1410                         result = STRING_TYPE;
1411                         break;
1412
1413                 case (BITOID):
1414                 case (VARBITOID):
1415                         result = BITSTRING_TYPE;
1416                         break;
1417
1418                 case (OIDOID):
1419                 case (REGPROCOID):
1420                 case (REGPROCEDUREOID):
1421                 case (REGOPEROID):
1422                 case (REGOPERATOROID):
1423                 case (REGCLASSOID):
1424                 case (REGTYPEOID):
1425                 case (INT2OID):
1426                 case (INT4OID):
1427                 case (INT8OID):
1428                 case (FLOAT4OID):
1429                 case (FLOAT8OID):
1430                 case (NUMERICOID):
1431                 case (CASHOID):
1432                         result = NUMERIC_TYPE;
1433                         break;
1434
1435                 case (DATEOID):
1436                 case (TIMEOID):
1437                 case (TIMETZOID):
1438                 case (ABSTIMEOID):
1439                 case (TIMESTAMPOID):
1440                 case (TIMESTAMPTZOID):
1441                         result = DATETIME_TYPE;
1442                         break;
1443
1444                 case (RELTIMEOID):
1445                 case (TINTERVALOID):
1446                 case (INTERVALOID):
1447                         result = TIMESPAN_TYPE;
1448                         break;
1449
1450                 case (POINTOID):
1451                 case (LSEGOID):
1452                 case (PATHOID):
1453                 case (BOXOID):
1454                 case (POLYGONOID):
1455                 case (LINEOID):
1456                 case (CIRCLEOID):
1457                         result = GEOMETRIC_TYPE;
1458                         break;
1459
1460                 case (INETOID):
1461                 case (CIDROID):
1462                         result = NETWORK_TYPE;
1463                         break;
1464
1465                 case (UNKNOWNOID):
1466                 case (InvalidOid):
1467                         result = UNKNOWN_TYPE;
1468                         break;
1469
1470                 case (RECORDOID):
1471                 case (CSTRINGOID):
1472                 case (ANYOID):
1473                 case (ANYARRAYOID):
1474                 case (VOIDOID):
1475                 case (TRIGGEROID):
1476                 case (LANGUAGE_HANDLEROID):
1477                 case (INTERNALOID):
1478                 case (OPAQUEOID):
1479                 case (ANYELEMENTOID):
1480                         result = GENERIC_TYPE;
1481                         break;
1482
1483                 default:
1484                         result = USER_TYPE;
1485                         break;
1486         }
1487         return result;
1488 }       /* TypeCategory() */
1489
1490
1491 /* IsPreferredType()
1492  *              Check if this type is a preferred type for the given category.
1493  *
1494  * If category is INVALID_TYPE, then we'll return TRUE for preferred types
1495  * of any category; otherwise, only for preferred types of that category.
1496  *
1497  * XXX This should be moved to system catalog lookups
1498  * to allow for better type extensibility.
1499  * - thomas 2001-09-30
1500  */
1501 bool
1502 IsPreferredType(CATEGORY category, Oid type)
1503 {
1504         Oid                     preftype;
1505
1506         if (category == INVALID_TYPE)
1507                 category = TypeCategory(type);
1508         else if (category != TypeCategory(type))
1509                 return false;
1510
1511         /*
1512          * This switch should agree with TypeCategory(), above.  Note that at this
1513          * point, category certainly matches the type.
1514          */
1515         switch (category)
1516         {
1517                 case (UNKNOWN_TYPE):
1518                 case (GENERIC_TYPE):
1519                         preftype = UNKNOWNOID;
1520                         break;
1521
1522                 case (BOOLEAN_TYPE):
1523                         preftype = BOOLOID;
1524                         break;
1525
1526                 case (STRING_TYPE):
1527                         preftype = TEXTOID;
1528                         break;
1529
1530                 case (BITSTRING_TYPE):
1531                         preftype = VARBITOID;
1532                         break;
1533
1534                 case (NUMERIC_TYPE):
1535                         if (type == OIDOID ||
1536                                 type == REGPROCOID ||
1537                                 type == REGPROCEDUREOID ||
1538                                 type == REGOPEROID ||
1539                                 type == REGOPERATOROID ||
1540                                 type == REGCLASSOID ||
1541                                 type == REGTYPEOID)
1542                                 preftype = OIDOID;
1543                         else
1544                                 preftype = FLOAT8OID;
1545                         break;
1546
1547                 case (DATETIME_TYPE):
1548                         if (type == DATEOID)
1549                                 preftype = TIMESTAMPOID;
1550                         else
1551                                 preftype = TIMESTAMPTZOID;
1552                         break;
1553
1554                 case (TIMESPAN_TYPE):
1555                         preftype = INTERVALOID;
1556                         break;
1557
1558                 case (GEOMETRIC_TYPE):
1559                         preftype = type;
1560                         break;
1561
1562                 case (NETWORK_TYPE):
1563                         preftype = INETOID;
1564                         break;
1565
1566                 case (USER_TYPE):
1567                         preftype = type;
1568                         break;
1569
1570                 default:
1571                         elog(ERROR, "unrecognized type category: %d", (int) category);
1572                         preftype = UNKNOWNOID;
1573                         break;
1574         }
1575
1576         return (type == preftype);
1577 }       /* IsPreferredType() */
1578
1579
1580 /* IsBinaryCoercible()
1581  *              Check if srctype is binary-coercible to targettype.
1582  *
1583  * This notion allows us to cheat and directly exchange values without
1584  * going through the trouble of calling a conversion function.  Note that
1585  * in general, this should only be an implementation shortcut.  Before 7.4,
1586  * this was also used as a heuristic for resolving overloaded functions and
1587  * operators, but that's basically a bad idea.
1588  *
1589  * As of 7.3, binary coercibility isn't hardwired into the code anymore.
1590  * We consider two types binary-coercible if there is an implicitly
1591  * invokable, no-function-needed pg_cast entry.  Also, a domain is always
1592  * binary-coercible to its base type, though *not* vice versa (in the other
1593  * direction, one must apply domain constraint checks before accepting the
1594  * value as legitimate).  We also need to special-case the polymorphic
1595  * ANYARRAY type.
1596  *
1597  * This function replaces IsBinaryCompatible(), which was an inherently
1598  * symmetric test.      Since the pg_cast entries aren't necessarily symmetric,
1599  * the order of the operands is now significant.
1600  */
1601 bool
1602 IsBinaryCoercible(Oid srctype, Oid targettype)
1603 {
1604         HeapTuple       tuple;
1605         Form_pg_cast castForm;
1606         bool            result;
1607
1608         /* Fast path if same type */
1609         if (srctype == targettype)
1610                 return true;
1611
1612         /* If srctype is a domain, reduce to its base type */
1613         if (OidIsValid(srctype))
1614                 srctype = getBaseType(srctype);
1615
1616         /* Somewhat-fast path for domain -> base type case */
1617         if (srctype == targettype)
1618                 return true;
1619
1620         /* Also accept any array type as coercible to ANYARRAY */
1621         if (targettype == ANYARRAYOID)
1622                 if (get_element_type(srctype) != InvalidOid)
1623                         return true;
1624
1625         /* Else look in pg_cast */
1626         tuple = SearchSysCache(CASTSOURCETARGET,
1627                                                    ObjectIdGetDatum(srctype),
1628                                                    ObjectIdGetDatum(targettype),
1629                                                    0, 0);
1630         if (!HeapTupleIsValid(tuple))
1631                 return false;                   /* no cast */
1632         castForm = (Form_pg_cast) GETSTRUCT(tuple);
1633
1634         result = (castForm->castfunc == InvalidOid &&
1635                           castForm->castcontext == COERCION_CODE_IMPLICIT);
1636
1637         ReleaseSysCache(tuple);
1638
1639         return result;
1640 }
1641
1642
1643 /*
1644  * find_coercion_pathway
1645  *              Look for a coercion pathway between two types.
1646  *
1647  * ccontext determines the set of available casts.
1648  *
1649  * If we find a suitable entry in pg_cast, return TRUE, and set *funcid
1650  * to the castfunc value, which may be InvalidOid for a binary-compatible
1651  * coercion.
1652  *
1653  * NOTE: *funcid == InvalidOid does not necessarily mean that no work is
1654  * needed to do the coercion; if the target is a domain then we may need to
1655  * apply domain constraint checking.  If you want to check for a zero-effort
1656  * conversion then use IsBinaryCoercible().
1657  */
1658 bool
1659 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
1660                                           CoercionContext ccontext,
1661                                           Oid *funcid)
1662 {
1663         bool            result = false;
1664         HeapTuple       tuple;
1665
1666         *funcid = InvalidOid;
1667
1668         /* Perhaps the types are domains; if so, look at their base types */
1669         if (OidIsValid(sourceTypeId))
1670                 sourceTypeId = getBaseType(sourceTypeId);
1671         if (OidIsValid(targetTypeId))
1672                 targetTypeId = getBaseType(targetTypeId);
1673
1674         /* Domains are always coercible to and from their base type */
1675         if (sourceTypeId == targetTypeId)
1676                 return true;
1677
1678         /* Look in pg_cast */
1679         tuple = SearchSysCache(CASTSOURCETARGET,
1680                                                    ObjectIdGetDatum(sourceTypeId),
1681                                                    ObjectIdGetDatum(targetTypeId),
1682                                                    0, 0);
1683
1684         if (HeapTupleIsValid(tuple))
1685         {
1686                 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1687                 CoercionContext castcontext;
1688
1689                 /* convert char value for castcontext to CoercionContext enum */
1690                 switch (castForm->castcontext)
1691                 {
1692                         case COERCION_CODE_IMPLICIT:
1693                                 castcontext = COERCION_IMPLICIT;
1694                                 break;
1695                         case COERCION_CODE_ASSIGNMENT:
1696                                 castcontext = COERCION_ASSIGNMENT;
1697                                 break;
1698                         case COERCION_CODE_EXPLICIT:
1699                                 castcontext = COERCION_EXPLICIT;
1700                                 break;
1701                         default:
1702                                 elog(ERROR, "unrecognized castcontext: %d",
1703                                          (int) castForm->castcontext);
1704                                 castcontext = 0;        /* keep compiler quiet */
1705                                 break;
1706                 }
1707
1708                 /* Rely on ordering of enum for correct behavior here */
1709                 if (ccontext >= castcontext)
1710                 {
1711                         *funcid = castForm->castfunc;
1712                         result = true;
1713                 }
1714
1715                 ReleaseSysCache(tuple);
1716         }
1717         else
1718         {
1719                 /*
1720                  * If there's no pg_cast entry, perhaps we are dealing with a pair of
1721                  * array types.  If so, and if the element types have a suitable cast,
1722                  * use array_type_coerce() or array_type_length_coerce().
1723                  *
1724                  * Hack: disallow coercions to oidvector and int2vector, which
1725                  * otherwise tend to capture coercions that should go to "real" array
1726                  * types.  We want those types to be considered "real" arrays for many
1727                  * purposes, but not this one.  (Also, array_type_coerce isn't
1728                  * guaranteed to produce an output that meets the restrictions of
1729                  * these datatypes, such as being 1-dimensional.)
1730                  */
1731                 Oid                     targetElemType;
1732                 Oid                     sourceElemType;
1733                 Oid                     elemfuncid;
1734
1735                 if (targetTypeId == OIDVECTOROID || targetTypeId == INT2VECTOROID)
1736                         return false;
1737
1738                 if ((targetElemType = get_element_type(targetTypeId)) != InvalidOid &&
1739                         (sourceElemType = get_element_type(sourceTypeId)) != InvalidOid)
1740                 {
1741                         if (find_coercion_pathway(targetElemType, sourceElemType,
1742                                                                           ccontext, &elemfuncid))
1743                         {
1744                                 if (!OidIsValid(elemfuncid))
1745                                 {
1746                                         /* binary-compatible element type conversion */
1747                                         *funcid = F_ARRAY_TYPE_COERCE;
1748                                 }
1749                                 else
1750                                 {
1751                                         /* does the function take a typmod arg? */
1752                                         if (get_func_nargs(elemfuncid) > 1)
1753                                                 *funcid = F_ARRAY_TYPE_LENGTH_COERCE;
1754                                         else
1755                                                 *funcid = F_ARRAY_TYPE_COERCE;
1756                                 }
1757                                 result = true;
1758                         }
1759                 }
1760         }
1761
1762         return result;
1763 }
1764
1765
1766 /*
1767  * find_typmod_coercion_function -- does the given type need length coercion?
1768  *
1769  * If the target type possesses a pg_cast function from itself to itself,
1770  * it must need length coercion.
1771  *
1772  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
1773  *
1774  * If the given type is a varlena array type, we do not look for a coercion
1775  * function associated directly with the array type, but instead look for
1776  * one associated with the element type.  If one exists, we report
1777  * array_length_coerce() as the coercion function to use.
1778  */
1779 Oid
1780 find_typmod_coercion_function(Oid typeId)
1781 {
1782         Oid                     funcid = InvalidOid;
1783         bool            isArray = false;
1784         Type            targetType;
1785         Form_pg_type typeForm;
1786         HeapTuple       tuple;
1787
1788         targetType = typeidType(typeId);
1789         typeForm = (Form_pg_type) GETSTRUCT(targetType);
1790
1791         /* Check for a varlena array type (and not a domain) */
1792         if (typeForm->typelem != InvalidOid &&
1793                 typeForm->typlen == -1 &&
1794                 typeForm->typtype != 'd')
1795         {
1796                 /* Yes, switch our attention to the element type */
1797                 typeId = typeForm->typelem;
1798                 isArray = true;
1799         }
1800         ReleaseSysCache(targetType);
1801
1802         /* Look in pg_cast */
1803         tuple = SearchSysCache(CASTSOURCETARGET,
1804                                                    ObjectIdGetDatum(typeId),
1805                                                    ObjectIdGetDatum(typeId),
1806                                                    0, 0);
1807
1808         if (HeapTupleIsValid(tuple))
1809         {
1810                 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1811
1812                 funcid = castForm->castfunc;
1813                 ReleaseSysCache(tuple);
1814         }
1815
1816         /*
1817          * Now, if we did find a coercion function for an array element type,
1818          * report array_length_coerce() as the function to use.
1819          */
1820         if (isArray && OidIsValid(funcid))
1821                 funcid = F_ARRAY_LENGTH_COERCE;
1822
1823         return funcid;
1824 }