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