]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_coerce.c
Reduce hash size for compute_array_stats, compute_tsvector_stats.
[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-2012, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/parser/parse_coerce.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include "catalog/pg_cast.h"
18 #include "catalog/pg_class.h"
19 #include "catalog/pg_inherits_fn.h"
20 #include "catalog/pg_proc.h"
21 #include "catalog/pg_type.h"
22 #include "nodes/makefuncs.h"
23 #include "nodes/nodeFuncs.h"
24 #include "parser/parse_coerce.h"
25 #include "parser/parse_relation.h"
26 #include "parser/parse_type.h"
27 #include "utils/builtins.h"
28 #include "utils/lsyscache.h"
29 #include "utils/syscache.h"
30 #include "utils/typcache.h"
31
32
33 static Node *coerce_type_typmod(Node *node,
34                                    Oid targetTypeId, int32 targetTypMod,
35                                    CoercionForm cformat, int location,
36                                    bool isExplicit, bool hideInputCoercion);
37 static void hide_coercion_node(Node *node);
38 static Node *build_coercion_expression(Node *node,
39                                                   CoercionPathType pathtype,
40                                                   Oid funcId,
41                                                   Oid targetTypeId, int32 targetTypMod,
42                                                   CoercionForm cformat, int location,
43                                                   bool isExplicit);
44 static Node *coerce_record_to_complex(ParseState *pstate, Node *node,
45                                                  Oid targetTypeId,
46                                                  CoercionContext ccontext,
47                                                  CoercionForm cformat,
48                                                  int location);
49 static bool is_complex_array(Oid typid);
50 static bool typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId);
51
52
53 /*
54  * coerce_to_target_type()
55  *              Convert an expression to a target type and typmod.
56  *
57  * This is the general-purpose entry point for arbitrary type coercion
58  * operations.  Direct use of the component operations can_coerce_type,
59  * coerce_type, and coerce_type_typmod should be restricted to special
60  * cases (eg, when the conversion is expected to succeed).
61  *
62  * Returns the possibly-transformed expression tree, or NULL if the type
63  * conversion is not possible.  (We do this, rather than ereport'ing directly,
64  * so that callers can generate custom error messages indicating context.)
65  *
66  * pstate - parse state (can be NULL, see coerce_type)
67  * expr - input expression tree (already transformed by transformExpr)
68  * exprtype - result type of expr
69  * targettype - desired result type
70  * targettypmod - desired result typmod
71  * ccontext, cformat - context indicators to control coercions
72  * location - parse location of the coercion request, or -1 if unknown/implicit
73  */
74 Node *
75 coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype,
76                                           Oid targettype, int32 targettypmod,
77                                           CoercionContext ccontext,
78                                           CoercionForm cformat,
79                                           int location)
80 {
81         Node       *result;
82         Node       *origexpr;
83
84         if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
85                 return NULL;
86
87         /*
88          * If the input has a CollateExpr at the top, strip it off, perform the
89          * coercion, and put a new one back on.  This is annoying since it
90          * duplicates logic in coerce_type, but if we don't do this then it's too
91          * hard to tell whether coerce_type actually changed anything, and we
92          * *must* know that to avoid possibly calling hide_coercion_node on
93          * something that wasn't generated by coerce_type.  Note that if there are
94          * multiple stacked CollateExprs, we just discard all but the topmost.
95          */
96         origexpr = expr;
97         while (expr && IsA(expr, CollateExpr))
98                 expr = (Node *) ((CollateExpr *) expr)->arg;
99
100         result = coerce_type(pstate, expr, exprtype,
101                                                  targettype, targettypmod,
102                                                  ccontext, cformat, location);
103
104         /*
105          * If the target is a fixed-length type, it may need a length coercion as
106          * well as a type coercion.  If we find ourselves adding both, force the
107          * inner coercion node to implicit display form.
108          */
109         result = coerce_type_typmod(result,
110                                                                 targettype, targettypmod,
111                                                                 cformat, location,
112                                                                 (cformat != COERCE_IMPLICIT_CAST),
113                                                                 (result != expr && !IsA(result, Const)));
114
115         if (expr != origexpr)
116         {
117                 /* Reinstall top CollateExpr */
118                 CollateExpr *coll = (CollateExpr *) origexpr;
119                 CollateExpr *newcoll = makeNode(CollateExpr);
120
121                 newcoll->arg = (Expr *) result;
122                 newcoll->collOid = coll->collOid;
123                 newcoll->location = coll->location;
124                 result = (Node *) newcoll;
125         }
126
127         return result;
128 }
129
130
131 /*
132  * coerce_type()
133  *              Convert an expression to a different type.
134  *
135  * The caller should already have determined that the coercion is possible;
136  * see can_coerce_type.
137  *
138  * Normally, no coercion to a typmod (length) is performed here.  The caller
139  * must call coerce_type_typmod as well, if a typmod constraint is wanted.
140  * (But if the target type is a domain, it may internally contain a
141  * typmod constraint, which will be applied inside coerce_to_domain.)
142  * In some cases pg_cast specifies a type coercion function that also
143  * applies length conversion, and in those cases only, the result will
144  * already be properly coerced to the specified typmod.
145  *
146  * pstate is only used in the case that we are able to resolve the type of
147  * a previously UNKNOWN Param.  It is okay to pass pstate = NULL if the
148  * caller does not want type information updated for Params.
149  *
150  * Note: this function must not modify the given expression tree, only add
151  * decoration on top of it.  See transformSetOperationTree, for example.
152  */
153 Node *
154 coerce_type(ParseState *pstate, Node *node,
155                         Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
156                         CoercionContext ccontext, CoercionForm cformat, int location)
157 {
158         Node       *result;
159         CoercionPathType pathtype;
160         Oid                     funcId;
161
162         if (targetTypeId == inputTypeId ||
163                 node == NULL)
164         {
165                 /* no conversion needed */
166                 return node;
167         }
168         if (targetTypeId == ANYOID ||
169                 targetTypeId == ANYELEMENTOID ||
170                 targetTypeId == ANYNONARRAYOID)
171         {
172                 /*
173                  * Assume can_coerce_type verified that implicit coercion is okay.
174                  *
175                  * Note: by returning the unmodified node here, we are saying that
176                  * it's OK to treat an UNKNOWN constant as a valid input for a
177                  * function accepting ANY, ANYELEMENT, or ANYNONARRAY.  This should be
178                  * all right, since an UNKNOWN value is still a perfectly valid Datum.
179                  *
180                  * NB: we do NOT want a RelabelType here: the exposed type of the
181                  * function argument must be its actual type, not the polymorphic
182                  * pseudotype.
183                  */
184                 return node;
185         }
186         if (targetTypeId == ANYARRAYOID ||
187                 targetTypeId == ANYENUMOID ||
188                 targetTypeId == ANYRANGEOID)
189         {
190                 /*
191                  * Assume can_coerce_type verified that implicit coercion is okay.
192                  *
193                  * These cases are unlike the ones above because the exposed type of
194                  * the argument must be an actual array, enum, or range type.  In
195                  * particular the argument must *not* be an UNKNOWN constant.  If it
196                  * is, we just fall through; below, we'll call anyarray_in,
197                  * anyenum_in, or anyrange_in, which will produce an error.  Also, if
198                  * what we have is a domain over array, enum, or range, we have to
199                  * relabel it to its base type.
200                  *
201                  * Note: currently, we can't actually see a domain-over-enum here,
202                  * since the other functions in this file will not match such a
203                  * parameter to ANYENUM.  But that should get changed eventually.
204                  */
205                 if (inputTypeId != UNKNOWNOID)
206                 {
207                         Oid                     baseTypeId = getBaseType(inputTypeId);
208
209                         if (baseTypeId != inputTypeId)
210                         {
211                                 RelabelType *r = makeRelabelType((Expr *) node,
212                                                                                                  baseTypeId, -1,
213                                                                                                  InvalidOid,
214                                                                                                  cformat);
215
216                                 r->location = location;
217                                 return (Node *) r;
218                         }
219                         /* Not a domain type, so return it as-is */
220                         return node;
221                 }
222         }
223         if (inputTypeId == UNKNOWNOID && IsA(node, Const))
224         {
225                 /*
226                  * Input is a string constant with previously undetermined type. Apply
227                  * the target type's typinput function to it to produce a constant of
228                  * the target type.
229                  *
230                  * NOTE: this case cannot be folded together with the other
231                  * constant-input case, since the typinput function does not
232                  * necessarily behave the same as a type conversion function. For
233                  * example, int4's typinput function will reject "1.2", whereas
234                  * float-to-int type conversion will round to integer.
235                  *
236                  * XXX if the typinput function is not immutable, we really ought to
237                  * postpone evaluation of the function call until runtime. But there
238                  * is no way to represent a typinput function call as an expression
239                  * tree, because C-string values are not Datums. (XXX This *is*
240                  * possible as of 7.3, do we want to do it?)
241                  */
242                 Const      *con = (Const *) node;
243                 Const      *newcon = makeNode(Const);
244                 Oid                     baseTypeId;
245                 int32           baseTypeMod;
246                 int32           inputTypeMod;
247                 Type            targetType;
248                 ParseCallbackState pcbstate;
249
250                 /*
251                  * If the target type is a domain, we want to call its base type's
252                  * input routine, not domain_in().      This is to avoid premature failure
253                  * when the domain applies a typmod: existing input routines follow
254                  * implicit-coercion semantics for length checks, which is not always
255                  * what we want here.  The needed check will be applied properly
256                  * inside coerce_to_domain().
257                  */
258                 baseTypeMod = targetTypeMod;
259                 baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
260
261                 /*
262                  * For most types we pass typmod -1 to the input routine, because
263                  * existing input routines follow implicit-coercion semantics for
264                  * length checks, which is not always what we want here.  Any length
265                  * constraint will be applied later by our caller.      An exception
266                  * however is the INTERVAL type, for which we *must* pass the typmod
267                  * or it won't be able to obey the bizarre SQL-spec input rules. (Ugly
268                  * as sin, but so is this part of the spec...)
269                  */
270                 if (baseTypeId == INTERVALOID)
271                         inputTypeMod = baseTypeMod;
272                 else
273                         inputTypeMod = -1;
274
275                 targetType = typeidType(baseTypeId);
276
277                 newcon->consttype = baseTypeId;
278                 newcon->consttypmod = inputTypeMod;
279                 newcon->constcollid = typeTypeCollation(targetType);
280                 newcon->constlen = typeLen(targetType);
281                 newcon->constbyval = typeByVal(targetType);
282                 newcon->constisnull = con->constisnull;
283
284                 /*
285                  * We use the original literal's location regardless of the position
286                  * of the coercion.  This is a change from pre-9.2 behavior, meant to
287                  * simplify life for pg_stat_statements.
288                  */
289                 newcon->location = con->location;
290
291                 /*
292                  * Set up to point at the constant's text if the input routine throws
293                  * an error.
294                  */
295                 setup_parser_errposition_callback(&pcbstate, pstate, con->location);
296
297                 /*
298                  * We assume here that UNKNOWN's internal representation is the same
299                  * as CSTRING.
300                  */
301                 if (!con->constisnull)
302                         newcon->constvalue = stringTypeDatum(targetType,
303                                                                                         DatumGetCString(con->constvalue),
304                                                                                                  inputTypeMod);
305                 else
306                         newcon->constvalue = stringTypeDatum(targetType,
307                                                                                                  NULL,
308                                                                                                  inputTypeMod);
309
310                 cancel_parser_errposition_callback(&pcbstate);
311
312                 result = (Node *) newcon;
313
314                 /* If target is a domain, apply constraints. */
315                 if (baseTypeId != targetTypeId)
316                         result = coerce_to_domain(result,
317                                                                           baseTypeId, baseTypeMod,
318                                                                           targetTypeId,
319                                                                           cformat, location, false, false);
320
321                 ReleaseSysCache(targetType);
322
323                 return result;
324         }
325         if (IsA(node, Param) &&
326                 pstate != NULL && pstate->p_coerce_param_hook != NULL)
327         {
328                 /*
329                  * Allow the CoerceParamHook to decide what happens.  It can return a
330                  * transformed node (very possibly the same Param node), or return
331                  * NULL to indicate we should proceed with normal coercion.
332                  */
333                 result = (*pstate->p_coerce_param_hook) (pstate,
334                                                                                                  (Param *) node,
335                                                                                                  targetTypeId,
336                                                                                                  targetTypeMod,
337                                                                                                  location);
338                 if (result)
339                         return result;
340         }
341         if (IsA(node, CollateExpr))
342         {
343                 /*
344                  * If we have a COLLATE clause, we have to push the coercion
345                  * underneath the COLLATE.      This is really ugly, but there is little
346                  * choice because the above hacks on Consts and Params wouldn't happen
347                  * otherwise.  This kluge has consequences in coerce_to_target_type.
348                  */
349                 CollateExpr *coll = (CollateExpr *) node;
350                 CollateExpr *newcoll = makeNode(CollateExpr);
351
352                 newcoll->arg = (Expr *)
353                         coerce_type(pstate, (Node *) coll->arg,
354                                                 inputTypeId, targetTypeId, targetTypeMod,
355                                                 ccontext, cformat, location);
356                 newcoll->collOid = coll->collOid;
357                 newcoll->location = coll->location;
358                 return (Node *) newcoll;
359         }
360         pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
361                                                                          &funcId);
362         if (pathtype != COERCION_PATH_NONE)
363         {
364                 if (pathtype != COERCION_PATH_RELABELTYPE)
365                 {
366                         /*
367                          * Generate an expression tree representing run-time application
368                          * of the conversion function.  If we are dealing with a domain
369                          * target type, the conversion function will yield the base type,
370                          * and we need to extract the correct typmod to use from the
371                          * domain's typtypmod.
372                          */
373                         Oid                     baseTypeId;
374                         int32           baseTypeMod;
375
376                         baseTypeMod = targetTypeMod;
377                         baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
378
379                         result = build_coercion_expression(node, pathtype, funcId,
380                                                                                            baseTypeId, baseTypeMod,
381                                                                                            cformat, location,
382                                                                                   (cformat != COERCE_IMPLICIT_CAST));
383
384                         /*
385                          * If domain, coerce to the domain type and relabel with domain
386                          * type ID.  We can skip the internal length-coercion step if the
387                          * selected coercion function was a type-and-length coercion.
388                          */
389                         if (targetTypeId != baseTypeId)
390                                 result = coerce_to_domain(result, baseTypeId, baseTypeMod,
391                                                                                   targetTypeId,
392                                                                                   cformat, location, true,
393                                                                                   exprIsLengthCoercion(result,
394                                                                                                                            NULL));
395                 }
396                 else
397                 {
398                         /*
399                          * We don't need to do a physical conversion, but we do need to
400                          * attach a RelabelType node so that the expression will be seen
401                          * to have the intended type when inspected by higher-level code.
402                          *
403                          * Also, domains may have value restrictions beyond the base type
404                          * that must be accounted for.  If the destination is a domain
405                          * then we won't need a RelabelType node.
406                          */
407                         result = coerce_to_domain(node, InvalidOid, -1, targetTypeId,
408                                                                           cformat, location, false, false);
409                         if (result == node)
410                         {
411                                 /*
412                                  * XXX could we label result with exprTypmod(node) instead of
413                                  * default -1 typmod, to save a possible length-coercion
414                                  * later? Would work if both types have same interpretation of
415                                  * typmod, which is likely but not certain.
416                                  */
417                                 RelabelType *r = makeRelabelType((Expr *) result,
418                                                                                                  targetTypeId, -1,
419                                                                                                  InvalidOid,
420                                                                                                  cformat);
421
422                                 r->location = location;
423                                 result = (Node *) r;
424                         }
425                 }
426                 return result;
427         }
428         if (inputTypeId == RECORDOID &&
429                 ISCOMPLEX(targetTypeId))
430         {
431                 /* Coerce a RECORD to a specific complex type */
432                 return coerce_record_to_complex(pstate, node, targetTypeId,
433                                                                                 ccontext, cformat, location);
434         }
435         if (targetTypeId == RECORDOID &&
436                 ISCOMPLEX(inputTypeId))
437         {
438                 /* Coerce a specific complex type to RECORD */
439                 /* NB: we do NOT want a RelabelType here */
440                 return node;
441         }
442 #ifdef NOT_USED
443         if (inputTypeId == RECORDARRAYOID &&
444                 is_complex_array(targetTypeId))
445         {
446                 /* Coerce record[] to a specific complex array type */
447                 /* not implemented yet ... */
448         }
449 #endif
450         if (targetTypeId == RECORDARRAYOID &&
451                 is_complex_array(inputTypeId))
452         {
453                 /* Coerce a specific complex array type to record[] */
454                 /* NB: we do NOT want a RelabelType here */
455                 return node;
456         }
457         if (typeInheritsFrom(inputTypeId, targetTypeId)
458                 || typeIsOfTypedTable(inputTypeId, targetTypeId))
459         {
460                 /*
461                  * Input class type is a subclass of target, so generate an
462                  * appropriate runtime conversion (removing unneeded columns and
463                  * possibly rearranging the ones that are wanted).
464                  */
465                 ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
466
467                 r->arg = (Expr *) node;
468                 r->resulttype = targetTypeId;
469                 r->convertformat = cformat;
470                 r->location = location;
471                 return (Node *) r;
472         }
473         /* If we get here, caller blew it */
474         elog(ERROR, "failed to find conversion function from %s to %s",
475                  format_type_be(inputTypeId), format_type_be(targetTypeId));
476         return NULL;                            /* keep compiler quiet */
477 }
478
479
480 /*
481  * can_coerce_type()
482  *              Can input_typeids be coerced to target_typeids?
483  *
484  * We must be told the context (CAST construct, assignment, implicit coercion)
485  * as this determines the set of available casts.
486  */
487 bool
488 can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids,
489                                 CoercionContext ccontext)
490 {
491         bool            have_generics = false;
492         int                     i;
493
494         /* run through argument list... */
495         for (i = 0; i < nargs; i++)
496         {
497                 Oid                     inputTypeId = input_typeids[i];
498                 Oid                     targetTypeId = target_typeids[i];
499                 CoercionPathType pathtype;
500                 Oid                     funcId;
501
502                 /* no problem if same type */
503                 if (inputTypeId == targetTypeId)
504                         continue;
505
506                 /* accept if target is ANY */
507                 if (targetTypeId == ANYOID)
508                         continue;
509
510                 /* accept if target is polymorphic, for now */
511                 if (IsPolymorphicType(targetTypeId))
512                 {
513                         have_generics = true;           /* do more checking later */
514                         continue;
515                 }
516
517                 /*
518                  * If input is an untyped string constant, assume we can convert it to
519                  * anything.
520                  */
521                 if (inputTypeId == UNKNOWNOID)
522                         continue;
523
524                 /*
525                  * If pg_cast shows that we can coerce, accept.  This test now covers
526                  * both binary-compatible and coercion-function cases.
527                  */
528                 pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
529                                                                                  &funcId);
530                 if (pathtype != COERCION_PATH_NONE)
531                         continue;
532
533                 /*
534                  * If input is RECORD and target is a composite type, assume we can
535                  * coerce (may need tighter checking here)
536                  */
537                 if (inputTypeId == RECORDOID &&
538                         ISCOMPLEX(targetTypeId))
539                         continue;
540
541                 /*
542                  * If input is a composite type and target is RECORD, accept
543                  */
544                 if (targetTypeId == RECORDOID &&
545                         ISCOMPLEX(inputTypeId))
546                         continue;
547
548 #ifdef NOT_USED                                 /* not implemented yet */
549
550                 /*
551                  * If input is record[] and target is a composite array type, assume
552                  * we can coerce (may need tighter checking here)
553                  */
554                 if (inputTypeId == RECORDARRAYOID &&
555                         is_complex_array(targetTypeId))
556                         continue;
557 #endif
558
559                 /*
560                  * If input is a composite array type and target is record[], accept
561                  */
562                 if (targetTypeId == RECORDARRAYOID &&
563                         is_complex_array(inputTypeId))
564                         continue;
565
566                 /*
567                  * If input is a class type that inherits from target, accept
568                  */
569                 if (typeInheritsFrom(inputTypeId, targetTypeId)
570                         || typeIsOfTypedTable(inputTypeId, targetTypeId))
571                         continue;
572
573                 /*
574                  * Else, cannot coerce at this argument position
575                  */
576                 return false;
577         }
578
579         /* If we found any generic argument types, cross-check them */
580         if (have_generics)
581         {
582                 if (!check_generic_type_consistency(input_typeids, target_typeids,
583                                                                                         nargs))
584                         return false;
585         }
586
587         return true;
588 }
589
590
591 /*
592  * Create an expression tree to represent coercion to a domain type.
593  *
594  * 'arg': input expression
595  * 'baseTypeId': base type of domain, if known (pass InvalidOid if caller
596  *              has not bothered to look this up)
597  * 'baseTypeMod': base type typmod of domain, if known (pass -1 if caller
598  *              has not bothered to look this up)
599  * 'typeId': target type to coerce to
600  * 'cformat': coercion format
601  * 'location': coercion request location
602  * 'hideInputCoercion': if true, hide the input coercion under this one.
603  * 'lengthCoercionDone': if true, caller already accounted for length,
604  *              ie the input is already of baseTypMod as well as baseTypeId.
605  *
606  * If the target type isn't a domain, the given 'arg' is returned as-is.
607  */
608 Node *
609 coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId,
610                                  CoercionForm cformat, int location,
611                                  bool hideInputCoercion,
612                                  bool lengthCoercionDone)
613 {
614         CoerceToDomain *result;
615
616         /* Get the base type if it hasn't been supplied */
617         if (baseTypeId == InvalidOid)
618                 baseTypeId = getBaseTypeAndTypmod(typeId, &baseTypeMod);
619
620         /* If it isn't a domain, return the node as it was passed in */
621         if (baseTypeId == typeId)
622                 return arg;
623
624         /* Suppress display of nested coercion steps */
625         if (hideInputCoercion)
626                 hide_coercion_node(arg);
627
628         /*
629          * If the domain applies a typmod to its base type, build the appropriate
630          * coercion step.  Mark it implicit for display purposes, because we don't
631          * want it shown separately by ruleutils.c; but the isExplicit flag passed
632          * to the conversion function depends on the manner in which the domain
633          * coercion is invoked, so that the semantics of implicit and explicit
634          * coercion differ.  (Is that really the behavior we want?)
635          *
636          * NOTE: because we apply this as part of the fixed expression structure,
637          * ALTER DOMAIN cannot alter the typtypmod.  But it's unclear that that
638          * would be safe to do anyway, without lots of knowledge about what the
639          * base type thinks the typmod means.
640          */
641         if (!lengthCoercionDone)
642         {
643                 if (baseTypeMod >= 0)
644                         arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
645                                                                          COERCE_IMPLICIT_CAST, location,
646                                                                          (cformat != COERCE_IMPLICIT_CAST),
647                                                                          false);
648         }
649
650         /*
651          * Now build the domain coercion node.  This represents run-time checking
652          * of any constraints currently attached to the domain.  This also ensures
653          * that the expression is properly labeled as to result type.
654          */
655         result = makeNode(CoerceToDomain);
656         result->arg = (Expr *) arg;
657         result->resulttype = typeId;
658         result->resulttypmod = -1;      /* currently, always -1 for domains */
659         /* resultcollid will be set by parse_collate.c */
660         result->coercionformat = cformat;
661         result->location = location;
662
663         return (Node *) result;
664 }
665
666
667 /*
668  * coerce_type_typmod()
669  *              Force a value to a particular typmod, if meaningful and possible.
670  *
671  * This is applied to values that are going to be stored in a relation
672  * (where we have an atttypmod for the column) as well as values being
673  * explicitly CASTed (where the typmod comes from the target type spec).
674  *
675  * The caller must have already ensured that the value is of the correct
676  * type, typically by applying coerce_type.
677  *
678  * cformat determines the display properties of the generated node (if any),
679  * while isExplicit may affect semantics.  If hideInputCoercion is true
680  * *and* we generate a node, the input node is forced to IMPLICIT display
681  * form, so that only the typmod coercion node will be visible when
682  * displaying the expression.
683  *
684  * NOTE: this does not need to work on domain types, because any typmod
685  * coercion for a domain is considered to be part of the type coercion
686  * needed to produce the domain value in the first place.  So, no getBaseType.
687  */
688 static Node *
689 coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
690                                    CoercionForm cformat, int location,
691                                    bool isExplicit, bool hideInputCoercion)
692 {
693         CoercionPathType pathtype;
694         Oid                     funcId;
695
696         /*
697          * A negative typmod is assumed to mean that no coercion is wanted. Also,
698          * skip coercion if already done.
699          */
700         if (targetTypMod < 0 || targetTypMod == exprTypmod(node))
701                 return node;
702
703         pathtype = find_typmod_coercion_function(targetTypeId, &funcId);
704
705         if (pathtype != COERCION_PATH_NONE)
706         {
707                 /* Suppress display of nested coercion steps */
708                 if (hideInputCoercion)
709                         hide_coercion_node(node);
710
711                 node = build_coercion_expression(node, pathtype, funcId,
712                                                                                  targetTypeId, targetTypMod,
713                                                                                  cformat, location,
714                                                                                  isExplicit);
715         }
716
717         return node;
718 }
719
720 /*
721  * Mark a coercion node as IMPLICIT so it will never be displayed by
722  * ruleutils.c.  We use this when we generate a nest of coercion nodes
723  * to implement what is logically one conversion; the inner nodes are
724  * forced to IMPLICIT_CAST format.      This does not change their semantics,
725  * only display behavior.
726  *
727  * It is caller error to call this on something that doesn't have a
728  * CoercionForm field.
729  */
730 static void
731 hide_coercion_node(Node *node)
732 {
733         if (IsA(node, FuncExpr))
734                 ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
735         else if (IsA(node, RelabelType))
736                 ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
737         else if (IsA(node, CoerceViaIO))
738                 ((CoerceViaIO *) node)->coerceformat = COERCE_IMPLICIT_CAST;
739         else if (IsA(node, ArrayCoerceExpr))
740                 ((ArrayCoerceExpr *) node)->coerceformat = COERCE_IMPLICIT_CAST;
741         else if (IsA(node, ConvertRowtypeExpr))
742                 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
743         else if (IsA(node, RowExpr))
744                 ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
745         else if (IsA(node, CoerceToDomain))
746                 ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
747         else
748                 elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
749 }
750
751 /*
752  * build_coercion_expression()
753  *              Construct an expression tree for applying a pg_cast entry.
754  *
755  * This is used for both type-coercion and length-coercion operations,
756  * since there is no difference in terms of the calling convention.
757  */
758 static Node *
759 build_coercion_expression(Node *node,
760                                                   CoercionPathType pathtype,
761                                                   Oid funcId,
762                                                   Oid targetTypeId, int32 targetTypMod,
763                                                   CoercionForm cformat, int location,
764                                                   bool isExplicit)
765 {
766         int                     nargs = 0;
767
768         if (OidIsValid(funcId))
769         {
770                 HeapTuple       tp;
771                 Form_pg_proc procstruct;
772
773                 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcId));
774                 if (!HeapTupleIsValid(tp))
775                         elog(ERROR, "cache lookup failed for function %u", funcId);
776                 procstruct = (Form_pg_proc) GETSTRUCT(tp);
777
778                 /*
779                  * These Asserts essentially check that function is a legal coercion
780                  * function.  We can't make the seemingly obvious tests on prorettype
781                  * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
782                  * various binary-compatibility cases.
783                  */
784                 /* Assert(targetTypeId == procstruct->prorettype); */
785                 Assert(!procstruct->proretset);
786                 Assert(!procstruct->proisagg);
787                 Assert(!procstruct->proiswindow);
788                 nargs = procstruct->pronargs;
789                 Assert(nargs >= 1 && nargs <= 3);
790                 /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
791                 Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
792                 Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
793
794                 ReleaseSysCache(tp);
795         }
796
797         if (pathtype == COERCION_PATH_FUNC)
798         {
799                 /* We build an ordinary FuncExpr with special arguments */
800                 FuncExpr   *fexpr;
801                 List       *args;
802                 Const      *cons;
803
804                 Assert(OidIsValid(funcId));
805
806                 args = list_make1(node);
807
808                 if (nargs >= 2)
809                 {
810                         /* Pass target typmod as an int4 constant */
811                         cons = makeConst(INT4OID,
812                                                          -1,
813                                                          InvalidOid,
814                                                          sizeof(int32),
815                                                          Int32GetDatum(targetTypMod),
816                                                          false,
817                                                          true);
818
819                         args = lappend(args, cons);
820                 }
821
822                 if (nargs == 3)
823                 {
824                         /* Pass it a boolean isExplicit parameter, too */
825                         cons = makeConst(BOOLOID,
826                                                          -1,
827                                                          InvalidOid,
828                                                          sizeof(bool),
829                                                          BoolGetDatum(isExplicit),
830                                                          false,
831                                                          true);
832
833                         args = lappend(args, cons);
834                 }
835
836                 fexpr = makeFuncExpr(funcId, targetTypeId, args,
837                                                          InvalidOid, InvalidOid, cformat);
838                 fexpr->location = location;
839                 return (Node *) fexpr;
840         }
841         else if (pathtype == COERCION_PATH_ARRAYCOERCE)
842         {
843                 /* We need to build an ArrayCoerceExpr */
844                 ArrayCoerceExpr *acoerce = makeNode(ArrayCoerceExpr);
845
846                 acoerce->arg = (Expr *) node;
847                 acoerce->elemfuncid = funcId;
848                 acoerce->resulttype = targetTypeId;
849
850                 /*
851                  * Label the output as having a particular typmod only if we are
852                  * really invoking a length-coercion function, ie one with more than
853                  * one argument.
854                  */
855                 acoerce->resulttypmod = (nargs >= 2) ? targetTypMod : -1;
856                 /* resultcollid will be set by parse_collate.c */
857                 acoerce->isExplicit = isExplicit;
858                 acoerce->coerceformat = cformat;
859                 acoerce->location = location;
860
861                 return (Node *) acoerce;
862         }
863         else if (pathtype == COERCION_PATH_COERCEVIAIO)
864         {
865                 /* We need to build a CoerceViaIO node */
866                 CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
867
868                 Assert(!OidIsValid(funcId));
869
870                 iocoerce->arg = (Expr *) node;
871                 iocoerce->resulttype = targetTypeId;
872                 /* resultcollid will be set by parse_collate.c */
873                 iocoerce->coerceformat = cformat;
874                 iocoerce->location = location;
875
876                 return (Node *) iocoerce;
877         }
878         else
879         {
880                 elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
881                          (int) pathtype);
882                 return NULL;                    /* keep compiler quiet */
883         }
884 }
885
886
887 /*
888  * coerce_record_to_complex
889  *              Coerce a RECORD to a specific composite type.
890  *
891  * Currently we only support this for inputs that are RowExprs or whole-row
892  * Vars.
893  */
894 static Node *
895 coerce_record_to_complex(ParseState *pstate, Node *node,
896                                                  Oid targetTypeId,
897                                                  CoercionContext ccontext,
898                                                  CoercionForm cformat,
899                                                  int location)
900 {
901         RowExpr    *rowexpr;
902         TupleDesc       tupdesc;
903         List       *args = NIL;
904         List       *newargs;
905         int                     i;
906         int                     ucolno;
907         ListCell   *arg;
908
909         if (node && IsA(node, RowExpr))
910         {
911                 /*
912                  * Since the RowExpr must be of type RECORD, we needn't worry about it
913                  * containing any dropped columns.
914                  */
915                 args = ((RowExpr *) node)->args;
916         }
917         else if (node && IsA(node, Var) &&
918                          ((Var *) node)->varattno == InvalidAttrNumber)
919         {
920                 int                     rtindex = ((Var *) node)->varno;
921                 int                     sublevels_up = ((Var *) node)->varlevelsup;
922                 int                     vlocation = ((Var *) node)->location;
923                 RangeTblEntry *rte;
924
925                 rte = GetRTEByRangeTablePosn(pstate, rtindex, sublevels_up);
926                 expandRTE(rte, rtindex, sublevels_up, vlocation, false,
927                                   NULL, &args);
928         }
929         else
930                 ereport(ERROR,
931                                 (errcode(ERRCODE_CANNOT_COERCE),
932                                  errmsg("cannot cast type %s to %s",
933                                                 format_type_be(RECORDOID),
934                                                 format_type_be(targetTypeId)),
935                                  parser_coercion_errposition(pstate, location, node)));
936
937         tupdesc = lookup_rowtype_tupdesc(targetTypeId, -1);
938         newargs = NIL;
939         ucolno = 1;
940         arg = list_head(args);
941         for (i = 0; i < tupdesc->natts; i++)
942         {
943                 Node       *expr;
944                 Node       *cexpr;
945                 Oid                     exprtype;
946
947                 /* Fill in NULLs for dropped columns in rowtype */
948                 if (tupdesc->attrs[i]->attisdropped)
949                 {
950                         /*
951                          * can't use atttypid here, but it doesn't really matter what type
952                          * the Const claims to be.
953                          */
954                         newargs = lappend(newargs,
955                                                           makeNullConst(INT4OID, -1, InvalidOid));
956                         continue;
957                 }
958
959                 if (arg == NULL)
960                         ereport(ERROR,
961                                         (errcode(ERRCODE_CANNOT_COERCE),
962                                          errmsg("cannot cast type %s to %s",
963                                                         format_type_be(RECORDOID),
964                                                         format_type_be(targetTypeId)),
965                                          errdetail("Input has too few columns."),
966                                          parser_coercion_errposition(pstate, location, node)));
967                 expr = (Node *) lfirst(arg);
968                 exprtype = exprType(expr);
969
970                 cexpr = coerce_to_target_type(pstate,
971                                                                           expr, exprtype,
972                                                                           tupdesc->attrs[i]->atttypid,
973                                                                           tupdesc->attrs[i]->atttypmod,
974                                                                           ccontext,
975                                                                           COERCE_IMPLICIT_CAST,
976                                                                           -1);
977                 if (cexpr == NULL)
978                         ereport(ERROR,
979                                         (errcode(ERRCODE_CANNOT_COERCE),
980                                          errmsg("cannot cast type %s to %s",
981                                                         format_type_be(RECORDOID),
982                                                         format_type_be(targetTypeId)),
983                                          errdetail("Cannot cast type %s to %s in column %d.",
984                                                            format_type_be(exprtype),
985                                                            format_type_be(tupdesc->attrs[i]->atttypid),
986                                                            ucolno),
987                                          parser_coercion_errposition(pstate, location, expr)));
988                 newargs = lappend(newargs, cexpr);
989                 ucolno++;
990                 arg = lnext(arg);
991         }
992         if (arg != NULL)
993                 ereport(ERROR,
994                                 (errcode(ERRCODE_CANNOT_COERCE),
995                                  errmsg("cannot cast type %s to %s",
996                                                 format_type_be(RECORDOID),
997                                                 format_type_be(targetTypeId)),
998                                  errdetail("Input has too many columns."),
999                                  parser_coercion_errposition(pstate, location, node)));
1000
1001         ReleaseTupleDesc(tupdesc);
1002
1003         rowexpr = makeNode(RowExpr);
1004         rowexpr->args = newargs;
1005         rowexpr->row_typeid = targetTypeId;
1006         rowexpr->row_format = cformat;
1007         rowexpr->colnames = NIL;        /* not needed for named target type */
1008         rowexpr->location = location;
1009         return (Node *) rowexpr;
1010 }
1011
1012 /*
1013  * coerce_to_boolean()
1014  *              Coerce an argument of a construct that requires boolean input
1015  *              (AND, OR, NOT, etc).  Also check that input is not a set.
1016  *
1017  * Returns the possibly-transformed node tree.
1018  *
1019  * As with coerce_type, pstate may be NULL if no special unknown-Param
1020  * processing is wanted.
1021  */
1022 Node *
1023 coerce_to_boolean(ParseState *pstate, Node *node,
1024                                   const char *constructName)
1025 {
1026         Oid                     inputTypeId = exprType(node);
1027
1028         if (inputTypeId != BOOLOID)
1029         {
1030                 Node       *newnode;
1031
1032                 newnode = coerce_to_target_type(pstate, node, inputTypeId,
1033                                                                                 BOOLOID, -1,
1034                                                                                 COERCION_ASSIGNMENT,
1035                                                                                 COERCE_IMPLICIT_CAST,
1036                                                                                 -1);
1037                 if (newnode == NULL)
1038                         ereport(ERROR,
1039                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1040                         /* translator: first %s is name of a SQL construct, eg WHERE */
1041                                    errmsg("argument of %s must be type boolean, not type %s",
1042                                                   constructName, format_type_be(inputTypeId)),
1043                                          parser_errposition(pstate, exprLocation(node))));
1044                 node = newnode;
1045         }
1046
1047         if (expression_returns_set(node))
1048                 ereport(ERROR,
1049                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1050                 /* translator: %s is name of a SQL construct, eg WHERE */
1051                                  errmsg("argument of %s must not return a set",
1052                                                 constructName),
1053                                  parser_errposition(pstate, exprLocation(node))));
1054
1055         return node;
1056 }
1057
1058 /*
1059  * coerce_to_specific_type()
1060  *              Coerce an argument of a construct that requires a specific data type.
1061  *              Also check that input is not a set.
1062  *
1063  * Returns the possibly-transformed node tree.
1064  *
1065  * As with coerce_type, pstate may be NULL if no special unknown-Param
1066  * processing is wanted.
1067  */
1068 Node *
1069 coerce_to_specific_type(ParseState *pstate, Node *node,
1070                                                 Oid targetTypeId,
1071                                                 const char *constructName)
1072 {
1073         Oid                     inputTypeId = exprType(node);
1074
1075         if (inputTypeId != targetTypeId)
1076         {
1077                 Node       *newnode;
1078
1079                 newnode = coerce_to_target_type(pstate, node, inputTypeId,
1080                                                                                 targetTypeId, -1,
1081                                                                                 COERCION_ASSIGNMENT,
1082                                                                                 COERCE_IMPLICIT_CAST,
1083                                                                                 -1);
1084                 if (newnode == NULL)
1085                         ereport(ERROR,
1086                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1087                         /* translator: first %s is name of a SQL construct, eg LIMIT */
1088                                          errmsg("argument of %s must be type %s, not type %s",
1089                                                         constructName,
1090                                                         format_type_be(targetTypeId),
1091                                                         format_type_be(inputTypeId)),
1092                                          parser_errposition(pstate, exprLocation(node))));
1093                 node = newnode;
1094         }
1095
1096         if (expression_returns_set(node))
1097                 ereport(ERROR,
1098                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1099                 /* translator: %s is name of a SQL construct, eg LIMIT */
1100                                  errmsg("argument of %s must not return a set",
1101                                                 constructName),
1102                                  parser_errposition(pstate, exprLocation(node))));
1103
1104         return node;
1105 }
1106
1107
1108 /*
1109  * parser_coercion_errposition - report coercion error location, if possible
1110  *
1111  * We prefer to point at the coercion request (CAST, ::, etc) if possible;
1112  * but there may be no such location in the case of an implicit coercion.
1113  * In that case point at the input expression.
1114  *
1115  * XXX possibly this is more generally useful than coercion errors;
1116  * if so, should rename and place with parser_errposition.
1117  */
1118 int
1119 parser_coercion_errposition(ParseState *pstate,
1120                                                         int coerce_location,
1121                                                         Node *input_expr)
1122 {
1123         if (coerce_location >= 0)
1124                 return parser_errposition(pstate, coerce_location);
1125         else
1126                 return parser_errposition(pstate, exprLocation(input_expr));
1127 }
1128
1129
1130 /*
1131  * select_common_type()
1132  *              Determine the common supertype of a list of input expressions.
1133  *              This is used for determining the output type of CASE, UNION,
1134  *              and similar constructs.
1135  *
1136  * 'exprs' is a *nonempty* list of expressions.  Note that earlier items
1137  * in the list will be preferred if there is doubt.
1138  * 'context' is a phrase to use in the error message if we fail to select
1139  * a usable type.  Pass NULL to have the routine return InvalidOid
1140  * rather than throwing an error on failure.
1141  * 'which_expr': if not NULL, receives a pointer to the particular input
1142  * expression from which the result type was taken.
1143  */
1144 Oid
1145 select_common_type(ParseState *pstate, List *exprs, const char *context,
1146                                    Node **which_expr)
1147 {
1148         Node       *pexpr;
1149         Oid                     ptype;
1150         TYPCATEGORY pcategory;
1151         bool            pispreferred;
1152         ListCell   *lc;
1153
1154         Assert(exprs != NIL);
1155         pexpr = (Node *) linitial(exprs);
1156         lc = lnext(list_head(exprs));
1157         ptype = exprType(pexpr);
1158
1159         /*
1160          * If all input types are valid and exactly the same, just pick that type.
1161          * This is the only way that we will resolve the result as being a domain
1162          * type; otherwise domains are smashed to their base types for comparison.
1163          */
1164         if (ptype != UNKNOWNOID)
1165         {
1166                 for_each_cell(lc, lc)
1167                 {
1168                         Node       *nexpr = (Node *) lfirst(lc);
1169                         Oid                     ntype = exprType(nexpr);
1170
1171                         if (ntype != ptype)
1172                                 break;
1173                 }
1174                 if (lc == NULL)                 /* got to the end of the list? */
1175                 {
1176                         if (which_expr)
1177                                 *which_expr = pexpr;
1178                         return ptype;
1179                 }
1180         }
1181
1182         /*
1183          * Nope, so set up for the full algorithm.      Note that at this point, lc
1184          * points to the first list item with type different from pexpr's; we need
1185          * not re-examine any items the previous loop advanced over.
1186          */
1187         ptype = getBaseType(ptype);
1188         get_type_category_preferred(ptype, &pcategory, &pispreferred);
1189
1190         for_each_cell(lc, lc)
1191         {
1192                 Node       *nexpr = (Node *) lfirst(lc);
1193                 Oid                     ntype = getBaseType(exprType(nexpr));
1194
1195                 /* move on to next one if no new information... */
1196                 if (ntype != UNKNOWNOID && ntype != ptype)
1197                 {
1198                         TYPCATEGORY ncategory;
1199                         bool            nispreferred;
1200
1201                         get_type_category_preferred(ntype, &ncategory, &nispreferred);
1202                         if (ptype == UNKNOWNOID)
1203                         {
1204                                 /* so far, only unknowns so take anything... */
1205                                 pexpr = nexpr;
1206                                 ptype = ntype;
1207                                 pcategory = ncategory;
1208                                 pispreferred = nispreferred;
1209                         }
1210                         else if (ncategory != pcategory)
1211                         {
1212                                 /*
1213                                  * both types in different categories? then not much hope...
1214                                  */
1215                                 if (context == NULL)
1216                                         return InvalidOid;
1217                                 ereport(ERROR,
1218                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1219                                 /*------
1220                                   translator: first %s is name of a SQL construct, eg CASE */
1221                                                  errmsg("%s types %s and %s cannot be matched",
1222                                                                 context,
1223                                                                 format_type_be(ptype),
1224                                                                 format_type_be(ntype)),
1225                                                  parser_errposition(pstate, exprLocation(nexpr))));
1226                         }
1227                         else if (!pispreferred &&
1228                                          can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1229                                          !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1230                         {
1231                                 /*
1232                                  * take new type if can coerce to it implicitly but not the
1233                                  * other way; but if we have a preferred type, stay on it.
1234                                  */
1235                                 pexpr = nexpr;
1236                                 ptype = ntype;
1237                                 pcategory = ncategory;
1238                                 pispreferred = nispreferred;
1239                         }
1240                 }
1241         }
1242
1243         /*
1244          * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1245          * then resolve as type TEXT.  This situation comes up with constructs
1246          * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1247          * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1248          * output type as UNKNOWN, but that really doesn't work, because we'd
1249          * probably end up needing a runtime coercion from UNKNOWN to something
1250          * else, and we usually won't have it.  We need to coerce the unknown
1251          * literals while they are still literals, so a decision has to be made
1252          * now.
1253          */
1254         if (ptype == UNKNOWNOID)
1255                 ptype = TEXTOID;
1256
1257         if (which_expr)
1258                 *which_expr = pexpr;
1259         return ptype;
1260 }
1261
1262 /*
1263  * coerce_to_common_type()
1264  *              Coerce an expression to the given type.
1265  *
1266  * This is used following select_common_type() to coerce the individual
1267  * expressions to the desired type.  'context' is a phrase to use in the
1268  * error message if we fail to coerce.
1269  *
1270  * As with coerce_type, pstate may be NULL if no special unknown-Param
1271  * processing is wanted.
1272  */
1273 Node *
1274 coerce_to_common_type(ParseState *pstate, Node *node,
1275                                           Oid targetTypeId, const char *context)
1276 {
1277         Oid                     inputTypeId = exprType(node);
1278
1279         if (inputTypeId == targetTypeId)
1280                 return node;                    /* no work */
1281         if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
1282                 node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1283                                                    COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
1284         else
1285                 ereport(ERROR,
1286                                 (errcode(ERRCODE_CANNOT_COERCE),
1287                 /* translator: first %s is name of a SQL construct, eg CASE */
1288                                  errmsg("%s could not convert type %s to %s",
1289                                                 context,
1290                                                 format_type_be(inputTypeId),
1291                                                 format_type_be(targetTypeId)),
1292                                  parser_errposition(pstate, exprLocation(node))));
1293         return node;
1294 }
1295
1296 /*
1297  * check_generic_type_consistency()
1298  *              Are the actual arguments potentially compatible with a
1299  *              polymorphic function?
1300  *
1301  * The argument consistency rules are:
1302  *
1303  * 1) All arguments declared ANYELEMENT must have the same datatype.
1304  * 2) All arguments declared ANYARRAY must have the same datatype,
1305  *    which must be a varlena array type.
1306  * 3) All arguments declared ANYRANGE must have the same datatype,
1307  *    which must be a range type.
1308  * 4) If there are arguments of both ANYELEMENT and ANYARRAY, make sure the
1309  *    actual ANYELEMENT datatype is in fact the element type for the actual
1310  *    ANYARRAY datatype.
1311  * 5) Similarly, if there are arguments of both ANYELEMENT and ANYRANGE,
1312  *    make sure the actual ANYELEMENT datatype is in fact the subtype for
1313  *    the actual ANYRANGE type.
1314  * 6) ANYENUM is treated the same as ANYELEMENT except that if it is used
1315  *    (alone or in combination with plain ANYELEMENT), we add the extra
1316  *    condition that the ANYELEMENT type must be an enum.
1317  * 7) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1318  *    we add the extra condition that the ANYELEMENT type must not be an array.
1319  *    (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1320  *    is an extra restriction if not.)
1321  *
1322  * Domains over arrays match ANYARRAY, and are immediately flattened to their
1323  * base type.  (Thus, for example, we will consider it a match if one ANYARRAY
1324  * argument is a domain over int4[] while another one is just int4[].)  Also
1325  * notice that such a domain does *not* match ANYNONARRAY.
1326  *
1327  * Similarly, domains over ranges match ANYRANGE, and are immediately
1328  * flattened to their base type.
1329  *
1330  * Note that domains aren't currently considered to match ANYENUM,
1331  * even if their base type would match.
1332  *
1333  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1334  * argument, assume it is okay.
1335  *
1336  * If an input is of type ANYARRAY (ie, we know it's an array, but not
1337  * what element type), we will accept it as a match to an argument declared
1338  * ANYARRAY, so long as we don't have to determine an element type ---
1339  * that is, so long as there is no use of ANYELEMENT.  This is mostly for
1340  * backwards compatibility with the pre-7.4 behavior of ANYARRAY.
1341  *
1342  * We do not ereport here, but just return FALSE if a rule is violated.
1343  */
1344 bool
1345 check_generic_type_consistency(Oid *actual_arg_types,
1346                                                            Oid *declared_arg_types,
1347                                                            int nargs)
1348 {
1349         int                     j;
1350         Oid                     elem_typeid = InvalidOid;
1351         Oid                     array_typeid = InvalidOid;
1352         Oid                     array_typelem;
1353         Oid                     range_typeid = InvalidOid;
1354         Oid                     range_typelem;
1355         bool            have_anyelement = false;
1356         bool            have_anynonarray = false;
1357         bool            have_anyenum = false;
1358
1359         /*
1360          * Loop through the arguments to see if we have any that are polymorphic.
1361          * If so, require the actual types to be consistent.
1362          */
1363         for (j = 0; j < nargs; j++)
1364         {
1365                 Oid                     decl_type = declared_arg_types[j];
1366                 Oid                     actual_type = actual_arg_types[j];
1367
1368                 if (decl_type == ANYELEMENTOID ||
1369                         decl_type == ANYNONARRAYOID ||
1370                         decl_type == ANYENUMOID)
1371                 {
1372                         have_anyelement = true;
1373                         if (decl_type == ANYNONARRAYOID)
1374                                 have_anynonarray = true;
1375                         else if (decl_type == ANYENUMOID)
1376                                 have_anyenum = true;
1377                         if (actual_type == UNKNOWNOID)
1378                                 continue;
1379                         if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1380                                 return false;
1381                         elem_typeid = actual_type;
1382                 }
1383                 else if (decl_type == ANYARRAYOID)
1384                 {
1385                         if (actual_type == UNKNOWNOID)
1386                                 continue;
1387                         actual_type = getBaseType(actual_type);         /* flatten domains */
1388                         if (OidIsValid(array_typeid) && actual_type != array_typeid)
1389                                 return false;
1390                         array_typeid = actual_type;
1391                 }
1392                 else if (decl_type == ANYRANGEOID)
1393                 {
1394                         if (actual_type == UNKNOWNOID)
1395                                 continue;
1396                         actual_type = getBaseType(actual_type);         /* flatten domains */
1397                         if (OidIsValid(range_typeid) && actual_type != range_typeid)
1398                                 return false;
1399                         range_typeid = actual_type;
1400                 }
1401         }
1402
1403         /* Get the element type based on the array type, if we have one */
1404         if (OidIsValid(array_typeid))
1405         {
1406                 if (array_typeid == ANYARRAYOID)
1407                 {
1408                         /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1409                         if (have_anyelement)
1410                                 return false;
1411                         return true;
1412                 }
1413
1414                 array_typelem = get_element_type(array_typeid);
1415                 if (!OidIsValid(array_typelem))
1416                         return false;           /* should be an array, but isn't */
1417
1418                 if (!OidIsValid(elem_typeid))
1419                 {
1420                         /*
1421                          * if we don't have an element type yet, use the one we just got
1422                          */
1423                         elem_typeid = array_typelem;
1424                 }
1425                 else if (array_typelem != elem_typeid)
1426                 {
1427                         /* otherwise, they better match */
1428                         return false;
1429                 }
1430         }
1431
1432         /* Get the element type based on the range type, if we have one */
1433         if (OidIsValid(range_typeid))
1434         {
1435                 range_typelem = get_range_subtype(range_typeid);
1436                 if (!OidIsValid(range_typelem))
1437                         return false;           /* should be a range, but isn't */
1438
1439                 if (!OidIsValid(elem_typeid))
1440                 {
1441                         /*
1442                          * if we don't have an element type yet, use the one we just got
1443                          */
1444                         elem_typeid = range_typelem;
1445                 }
1446                 else if (range_typelem != elem_typeid)
1447                 {
1448                         /* otherwise, they better match */
1449                         return false;
1450                 }
1451         }
1452
1453         if (have_anynonarray)
1454         {
1455                 /* require the element type to not be an array or domain over array */
1456                 if (type_is_array_domain(elem_typeid))
1457                         return false;
1458         }
1459
1460         if (have_anyenum)
1461         {
1462                 /* require the element type to be an enum */
1463                 if (!type_is_enum(elem_typeid))
1464                         return false;
1465         }
1466
1467         /* Looks valid */
1468         return true;
1469 }
1470
1471 /*
1472  * enforce_generic_type_consistency()
1473  *              Make sure a polymorphic function is legally callable, and
1474  *              deduce actual argument and result types.
1475  *
1476  * If any polymorphic pseudotype is used in a function's arguments or
1477  * return type, we make sure the actual data types are consistent with
1478  * each other.  The argument consistency rules are shown above for
1479  * check_generic_type_consistency().
1480  *
1481  * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1482  * argument, we attempt to deduce the actual type it should have.  If
1483  * successful, we alter that position of declared_arg_types[] so that
1484  * make_fn_arguments will coerce the literal to the right thing.
1485  *
1486  * Rules are applied to the function's return type (possibly altering it)
1487  * if it is declared as a polymorphic type:
1488  *
1489  * 1) If return type is ANYARRAY, and any argument is ANYARRAY, use the
1490  *    argument's actual type as the function's return type.
1491  * 2) Similarly, if return type is ANYRANGE, and any argument is ANYRANGE,
1492  *    use the argument's actual type as the function's return type.
1493  * 3) If return type is ANYARRAY, no argument is ANYARRAY, but any argument is
1494  *    ANYELEMENT, use the actual type of the argument to determine the
1495  *    function's return type, i.e. the element type's corresponding array
1496  *    type.  (Note: similar behavior does not exist for ANYRANGE, because it's
1497  *    impossible to determine the range type from the subtype alone.)
1498  * 4) If return type is ANYARRAY, but no argument is ANYARRAY or ANYELEMENT,
1499  *    generate an error.  Similarly, if return type is ANYRANGE, but no
1500  *    argument is ANYRANGE, generate an error.  (These conditions are
1501  *    prevented by CREATE FUNCTION and therefore are not expected here.)
1502  * 5) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
1503  *    argument's actual type as the function's return type.
1504  * 6) If return type is ANYELEMENT, no argument is ANYELEMENT, but any argument
1505  *    is ANYARRAY or ANYRANGE, use the actual type of the argument to determine
1506  *    the function's return type, i.e. the array type's corresponding element
1507  *    type or the range type's corresponding subtype (or both, in which case
1508  *    they must match).
1509  * 7) If return type is ANYELEMENT, no argument is ANYELEMENT, ANYARRAY, or
1510  *    ANYRANGE, generate an error.  (This condition is prevented by CREATE
1511  *    FUNCTION and therefore is not expected here.)
1512  * 8) ANYENUM is treated the same as ANYELEMENT except that if it is used
1513  *    (alone or in combination with plain ANYELEMENT), we add the extra
1514  *    condition that the ANYELEMENT type must be an enum.
1515  * 9) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1516  *    we add the extra condition that the ANYELEMENT type must not be an array.
1517  *    (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1518  *    is an extra restriction if not.)
1519  *
1520  * Domains over arrays or ranges match ANYARRAY or ANYRANGE arguments,
1521  * respectively, and are immediately flattened to their base type. (In
1522  * particular, if the return type is also ANYARRAY or ANYRANGE, we'll set it
1523  * to the base type not the domain type.)
1524  *
1525  * When allow_poly is false, we are not expecting any of the actual_arg_types
1526  * to be polymorphic, and we should not return a polymorphic result type
1527  * either.  When allow_poly is true, it is okay to have polymorphic "actual"
1528  * arg types, and we can return ANYARRAY, ANYRANGE, or ANYELEMENT as the
1529  * result.  (This case is currently used only to check compatibility of an
1530  * aggregate's declaration with the underlying transfn.)
1531  *
1532  * A special case is that we could see ANYARRAY as an actual_arg_type even
1533  * when allow_poly is false (this is possible only because pg_statistic has
1534  * columns shown as anyarray in the catalogs).  We allow this to match a
1535  * declared ANYARRAY argument, but only if there is no ANYELEMENT argument
1536  * or result (since we can't determine a specific element type to match to
1537  * ANYELEMENT).  Note this means that functions taking ANYARRAY had better
1538  * behave sanely if applied to the pg_statistic columns; they can't just
1539  * assume that successive inputs are of the same actual element type.
1540  */
1541 Oid
1542 enforce_generic_type_consistency(Oid *actual_arg_types,
1543                                                                  Oid *declared_arg_types,
1544                                                                  int nargs,
1545                                                                  Oid rettype,
1546                                                                  bool allow_poly)
1547 {
1548         int                     j;
1549         bool            have_generics = false;
1550         bool            have_unknowns = false;
1551         Oid                     elem_typeid = InvalidOid;
1552         Oid                     array_typeid = InvalidOid;
1553         Oid                     range_typeid = InvalidOid;
1554         Oid                     array_typelem;
1555         Oid                     range_typelem;
1556         bool            have_anyelement = (rettype == ANYELEMENTOID ||
1557                                                                    rettype == ANYNONARRAYOID ||
1558                                                                    rettype == ANYENUMOID);
1559         bool            have_anynonarray = (rettype == ANYNONARRAYOID);
1560         bool            have_anyenum = (rettype == ANYENUMOID);
1561
1562         /*
1563          * Loop through the arguments to see if we have any that are polymorphic.
1564          * If so, require the actual types to be consistent.
1565          */
1566         for (j = 0; j < nargs; j++)
1567         {
1568                 Oid                     decl_type = declared_arg_types[j];
1569                 Oid                     actual_type = actual_arg_types[j];
1570
1571                 if (decl_type == ANYELEMENTOID ||
1572                         decl_type == ANYNONARRAYOID ||
1573                         decl_type == ANYENUMOID)
1574                 {
1575                         have_generics = have_anyelement = true;
1576                         if (decl_type == ANYNONARRAYOID)
1577                                 have_anynonarray = true;
1578                         else if (decl_type == ANYENUMOID)
1579                                 have_anyenum = true;
1580                         if (actual_type == UNKNOWNOID)
1581                         {
1582                                 have_unknowns = true;
1583                                 continue;
1584                         }
1585                         if (allow_poly && decl_type == actual_type)
1586                                 continue;               /* no new information here */
1587                         if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1588                                 ereport(ERROR,
1589                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1590                                 errmsg("arguments declared \"anyelement\" are not all alike"),
1591                                                  errdetail("%s versus %s",
1592                                                                    format_type_be(elem_typeid),
1593                                                                    format_type_be(actual_type))));
1594                         elem_typeid = actual_type;
1595                 }
1596                 else if (decl_type == ANYARRAYOID)
1597                 {
1598                         have_generics = true;
1599                         if (actual_type == UNKNOWNOID)
1600                         {
1601                                 have_unknowns = true;
1602                                 continue;
1603                         }
1604                         if (allow_poly && decl_type == actual_type)
1605                                 continue;               /* no new information here */
1606                         actual_type = getBaseType(actual_type);         /* flatten domains */
1607                         if (OidIsValid(array_typeid) && actual_type != array_typeid)
1608                                 ereport(ERROR,
1609                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1610                                  errmsg("arguments declared \"anyarray\" are not all alike"),
1611                                                  errdetail("%s versus %s",
1612                                                                    format_type_be(array_typeid),
1613                                                                    format_type_be(actual_type))));
1614                         array_typeid = actual_type;
1615                 }
1616                 else if (decl_type == ANYRANGEOID)
1617                 {
1618                         have_generics = true;
1619                         if (actual_type == UNKNOWNOID)
1620                         {
1621                                 have_unknowns = true;
1622                                 continue;
1623                         }
1624                         if (allow_poly && decl_type == actual_type)
1625                                 continue;               /* no new information here */
1626                         actual_type = getBaseType(actual_type);         /* flatten domains */
1627                         if (OidIsValid(range_typeid) && actual_type != range_typeid)
1628                                 ereport(ERROR,
1629                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1630                                  errmsg("arguments declared \"anyrange\" are not all alike"),
1631                                                  errdetail("%s versus %s",
1632                                                                    format_type_be(range_typeid),
1633                                                                    format_type_be(actual_type))));
1634                         range_typeid = actual_type;
1635                 }
1636         }
1637
1638         /*
1639          * Fast Track: if none of the arguments are polymorphic, return the
1640          * unmodified rettype.  We assume it can't be polymorphic either.
1641          */
1642         if (!have_generics)
1643                 return rettype;
1644
1645         /* Get the element type based on the array type, if we have one */
1646         if (OidIsValid(array_typeid))
1647         {
1648                 if (array_typeid == ANYARRAYOID && !have_anyelement)
1649                 {
1650                         /* Special case for ANYARRAY input: okay iff no ANYELEMENT */
1651                         array_typelem = ANYELEMENTOID;
1652                 }
1653                 else
1654                 {
1655                         array_typelem = get_element_type(array_typeid);
1656                         if (!OidIsValid(array_typelem))
1657                                 ereport(ERROR,
1658                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1659                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1660                                                                 format_type_be(array_typeid))));
1661                 }
1662
1663                 if (!OidIsValid(elem_typeid))
1664                 {
1665                         /*
1666                          * if we don't have an element type yet, use the one we just got
1667                          */
1668                         elem_typeid = array_typelem;
1669                 }
1670                 else if (array_typelem != elem_typeid)
1671                 {
1672                         /* otherwise, they better match */
1673                         ereport(ERROR,
1674                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1675                                          errmsg("argument declared \"anyarray\" is not consistent with argument declared \"anyelement\""),
1676                                          errdetail("%s versus %s",
1677                                                            format_type_be(array_typeid),
1678                                                            format_type_be(elem_typeid))));
1679                 }
1680         }
1681
1682         /* Get the element type based on the range type, if we have one */
1683         if (OidIsValid(range_typeid))
1684         {
1685                 if (range_typeid == ANYRANGEOID && !have_anyelement)
1686                 {
1687                         /* Special case for ANYRANGE input: okay iff no ANYELEMENT */
1688                         range_typelem = ANYELEMENTOID;
1689                 }
1690                 else
1691                 {
1692                         range_typelem = get_range_subtype(range_typeid);
1693                         if (!OidIsValid(range_typelem))
1694                                 ereport(ERROR,
1695                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1696                                                  errmsg("argument declared \"anyrange\" is not a range but type %s",
1697                                                                 format_type_be(range_typeid))));
1698                 }
1699
1700                 if (!OidIsValid(elem_typeid))
1701                 {
1702                         /*
1703                          * if we don't have an element type yet, use the one we just got
1704                          */
1705                         elem_typeid = range_typelem;
1706                 }
1707                 else if (range_typelem != elem_typeid)
1708                 {
1709                         /* otherwise, they better match */
1710                         ereport(ERROR,
1711                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1712                                          errmsg("argument declared \"anyrange\" is not consistent with argument declared \"anyelement\""),
1713                                          errdetail("%s versus %s",
1714                                                            format_type_be(range_typeid),
1715                                                            format_type_be(elem_typeid))));
1716                 }
1717         }
1718
1719         if (!OidIsValid(elem_typeid))
1720         {
1721                 if (allow_poly)
1722                 {
1723                         elem_typeid = ANYELEMENTOID;
1724                         array_typeid = ANYARRAYOID;
1725                         range_typeid = ANYRANGEOID;
1726                 }
1727                 else
1728                 {
1729                         /* Only way to get here is if all the generic args are UNKNOWN */
1730                         ereport(ERROR,
1731                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1732                                          errmsg("could not determine polymorphic type because input has type \"unknown\"")));
1733                 }
1734         }
1735
1736         if (have_anynonarray && elem_typeid != ANYELEMENTOID)
1737         {
1738                 /* require the element type to not be an array or domain over array */
1739                 if (type_is_array_domain(elem_typeid))
1740                         ereport(ERROR,
1741                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1742                                    errmsg("type matched to anynonarray is an array type: %s",
1743                                                   format_type_be(elem_typeid))));
1744         }
1745
1746         if (have_anyenum && elem_typeid != ANYELEMENTOID)
1747         {
1748                 /* require the element type to be an enum */
1749                 if (!type_is_enum(elem_typeid))
1750                         ereport(ERROR,
1751                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1752                                          errmsg("type matched to anyenum is not an enum type: %s",
1753                                                         format_type_be(elem_typeid))));
1754         }
1755
1756         /*
1757          * If we had any unknown inputs, re-scan to assign correct types
1758          */
1759         if (have_unknowns)
1760         {
1761                 for (j = 0; j < nargs; j++)
1762                 {
1763                         Oid                     decl_type = declared_arg_types[j];
1764                         Oid                     actual_type = actual_arg_types[j];
1765
1766                         if (actual_type != UNKNOWNOID)
1767                                 continue;
1768
1769                         if (decl_type == ANYELEMENTOID ||
1770                                 decl_type == ANYNONARRAYOID ||
1771                                 decl_type == ANYENUMOID)
1772                                 declared_arg_types[j] = elem_typeid;
1773                         else if (decl_type == ANYARRAYOID)
1774                         {
1775                                 if (!OidIsValid(array_typeid))
1776                                 {
1777                                         array_typeid = get_array_type(elem_typeid);
1778                                         if (!OidIsValid(array_typeid))
1779                                                 ereport(ERROR,
1780                                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1781                                                  errmsg("could not find array type for data type %s",
1782                                                                 format_type_be(elem_typeid))));
1783                                 }
1784                                 declared_arg_types[j] = array_typeid;
1785                         }
1786                         else if (decl_type == ANYRANGEOID)
1787                         {
1788                                 if (!OidIsValid(range_typeid))
1789                                 {
1790                                         ereport(ERROR,
1791                                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
1792                                                  errmsg("could not find range type for data type %s",
1793                                                                 format_type_be(elem_typeid))));
1794                                 }
1795                                 declared_arg_types[j] = range_typeid;
1796                         }
1797                 }
1798         }
1799
1800         /* if we return ANYARRAY use the appropriate argument type */
1801         if (rettype == ANYARRAYOID)
1802         {
1803                 if (!OidIsValid(array_typeid))
1804                 {
1805                         array_typeid = get_array_type(elem_typeid);
1806                         if (!OidIsValid(array_typeid))
1807                                 ereport(ERROR,
1808                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1809                                                  errmsg("could not find array type for data type %s",
1810                                                                 format_type_be(elem_typeid))));
1811                 }
1812                 return array_typeid;
1813         }
1814
1815         /* if we return ANYRANGE use the appropriate argument type */
1816         if (rettype == ANYRANGEOID)
1817         {
1818                 if (!OidIsValid(range_typeid))
1819                 {
1820                         ereport(ERROR,
1821                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
1822                                          errmsg("could not find range type for data type %s",
1823                                                         format_type_be(elem_typeid))));
1824                 }
1825                 return range_typeid;
1826         }
1827
1828         /* if we return ANYELEMENT use the appropriate argument type */
1829         if (rettype == ANYELEMENTOID ||
1830                 rettype == ANYNONARRAYOID ||
1831                 rettype == ANYENUMOID)
1832                 return elem_typeid;
1833
1834         /* we don't return a generic type; send back the original return type */
1835         return rettype;
1836 }
1837
1838 /*
1839  * resolve_generic_type()
1840  *              Deduce an individual actual datatype on the assumption that
1841  *              the rules for polymorphic types are being followed.
1842  *
1843  * declared_type is the declared datatype we want to resolve.
1844  * context_actual_type is the actual input datatype to some argument
1845  * that has declared datatype context_declared_type.
1846  *
1847  * If declared_type isn't polymorphic, we just return it.  Otherwise,
1848  * context_declared_type must be polymorphic, and we deduce the correct
1849  * return type based on the relationship of the two polymorphic types.
1850  */
1851 Oid
1852 resolve_generic_type(Oid declared_type,
1853                                          Oid context_actual_type,
1854                                          Oid context_declared_type)
1855 {
1856         if (declared_type == ANYARRAYOID)
1857         {
1858                 if (context_declared_type == ANYARRAYOID)
1859                 {
1860                         /*
1861                          * Use actual type, but it must be an array; or if it's a domain
1862                          * over array, use the base array type.
1863                          */
1864                         Oid                     context_base_type = getBaseType(context_actual_type);
1865                         Oid                     array_typelem = get_element_type(context_base_type);
1866
1867                         if (!OidIsValid(array_typelem))
1868                                 ereport(ERROR,
1869                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1870                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1871                                                                 format_type_be(context_base_type))));
1872                         return context_base_type;
1873                 }
1874                 else if (context_declared_type == ANYELEMENTOID ||
1875                                  context_declared_type == ANYNONARRAYOID ||
1876                                  context_declared_type == ANYENUMOID ||
1877                                  context_declared_type == ANYRANGEOID)
1878                 {
1879                         /* Use the array type corresponding to actual type */
1880                         Oid                     array_typeid = get_array_type(context_actual_type);
1881
1882                         if (!OidIsValid(array_typeid))
1883                                 ereport(ERROR,
1884                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1885                                                  errmsg("could not find array type for data type %s",
1886                                                                 format_type_be(context_actual_type))));
1887                         return array_typeid;
1888                 }
1889         }
1890         else if (declared_type == ANYELEMENTOID ||
1891                          declared_type == ANYNONARRAYOID ||
1892                          declared_type == ANYENUMOID ||
1893                          declared_type == ANYRANGEOID)
1894         {
1895                 if (context_declared_type == ANYARRAYOID)
1896                 {
1897                         /* Use the element type corresponding to actual type */
1898                         Oid                     context_base_type = getBaseType(context_actual_type);
1899                         Oid                     array_typelem = get_element_type(context_base_type);
1900
1901                         if (!OidIsValid(array_typelem))
1902                                 ereport(ERROR,
1903                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1904                                                  errmsg("argument declared \"anyarray\" is not an array but type %s",
1905                                                                 format_type_be(context_base_type))));
1906                         return array_typelem;
1907                 }
1908                 else if (context_declared_type == ANYRANGEOID)
1909                 {
1910                         /* Use the element type corresponding to actual type */
1911                         Oid                     context_base_type = getBaseType(context_actual_type);
1912                         Oid                     range_typelem = get_range_subtype(context_base_type);
1913
1914                         if (!OidIsValid(range_typelem))
1915                                 ereport(ERROR,
1916                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1917                                                  errmsg("argument declared \"anyrange\" is not a range but type %s",
1918                                                                 format_type_be(context_base_type))));
1919                         return range_typelem;
1920                 }
1921                 else if (context_declared_type == ANYELEMENTOID ||
1922                                  context_declared_type == ANYNONARRAYOID ||
1923                                  context_declared_type == ANYENUMOID)
1924                 {
1925                         /* Use the actual type; it doesn't matter if array or not */
1926                         return context_actual_type;
1927                 }
1928         }
1929         else
1930         {
1931                 /* declared_type isn't polymorphic, so return it as-is */
1932                 return declared_type;
1933         }
1934         /* If we get here, declared_type is polymorphic and context isn't */
1935         /* NB: this is a calling-code logic error, not a user error */
1936         elog(ERROR, "could not determine polymorphic type because context isn't polymorphic");
1937         return InvalidOid;                      /* keep compiler quiet */
1938 }
1939
1940
1941 /* TypeCategory()
1942  *              Assign a category to the specified type OID.
1943  *
1944  * NB: this must not return TYPCATEGORY_INVALID.
1945  */
1946 TYPCATEGORY
1947 TypeCategory(Oid type)
1948 {
1949         char            typcategory;
1950         bool            typispreferred;
1951
1952         get_type_category_preferred(type, &typcategory, &typispreferred);
1953         Assert(typcategory != TYPCATEGORY_INVALID);
1954         return (TYPCATEGORY) typcategory;
1955 }
1956
1957
1958 /* IsPreferredType()
1959  *              Check if this type is a preferred type for the given category.
1960  *
1961  * If category is TYPCATEGORY_INVALID, then we'll return TRUE for preferred
1962  * types of any category; otherwise, only for preferred types of that
1963  * category.
1964  */
1965 bool
1966 IsPreferredType(TYPCATEGORY category, Oid type)
1967 {
1968         char            typcategory;
1969         bool            typispreferred;
1970
1971         get_type_category_preferred(type, &typcategory, &typispreferred);
1972         if (category == typcategory || category == TYPCATEGORY_INVALID)
1973                 return typispreferred;
1974         else
1975                 return false;
1976 }
1977
1978
1979 /* IsBinaryCoercible()
1980  *              Check if srctype is binary-coercible to targettype.
1981  *
1982  * This notion allows us to cheat and directly exchange values without
1983  * going through the trouble of calling a conversion function.  Note that
1984  * in general, this should only be an implementation shortcut.  Before 7.4,
1985  * this was also used as a heuristic for resolving overloaded functions and
1986  * operators, but that's basically a bad idea.
1987  *
1988  * As of 7.3, binary coercibility isn't hardwired into the code anymore.
1989  * We consider two types binary-coercible if there is an implicitly
1990  * invokable, no-function-needed pg_cast entry.  Also, a domain is always
1991  * binary-coercible to its base type, though *not* vice versa (in the other
1992  * direction, one must apply domain constraint checks before accepting the
1993  * value as legitimate).  We also need to special-case various polymorphic
1994  * types.
1995  *
1996  * This function replaces IsBinaryCompatible(), which was an inherently
1997  * symmetric test.      Since the pg_cast entries aren't necessarily symmetric,
1998  * the order of the operands is now significant.
1999  */
2000 bool
2001 IsBinaryCoercible(Oid srctype, Oid targettype)
2002 {
2003         HeapTuple       tuple;
2004         Form_pg_cast castForm;
2005         bool            result;
2006
2007         /* Fast path if same type */
2008         if (srctype == targettype)
2009                 return true;
2010
2011         /* If srctype is a domain, reduce to its base type */
2012         if (OidIsValid(srctype))
2013                 srctype = getBaseType(srctype);
2014
2015         /* Somewhat-fast path for domain -> base type case */
2016         if (srctype == targettype)
2017                 return true;
2018
2019         /* Also accept any array type as coercible to ANYARRAY */
2020         if (targettype == ANYARRAYOID)
2021                 if (type_is_array(srctype))
2022                         return true;
2023
2024         /* Also accept any non-array type as coercible to ANYNONARRAY */
2025         if (targettype == ANYNONARRAYOID)
2026                 if (!type_is_array(srctype))
2027                         return true;
2028
2029         /* Also accept any enum type as coercible to ANYENUM */
2030         if (targettype == ANYENUMOID)
2031                 if (type_is_enum(srctype))
2032                         return true;
2033
2034         /* Also accept any range type as coercible to ANYRANGE */
2035         if (targettype == ANYRANGEOID)
2036                 if (type_is_range(srctype))
2037                         return true;
2038
2039         /* Also accept any composite type as coercible to RECORD */
2040         if (targettype == RECORDOID)
2041                 if (ISCOMPLEX(srctype))
2042                         return true;
2043
2044         /* Also accept any composite array type as coercible to RECORD[] */
2045         if (targettype == RECORDARRAYOID)
2046                 if (is_complex_array(srctype))
2047                         return true;
2048
2049         /* Else look in pg_cast */
2050         tuple = SearchSysCache2(CASTSOURCETARGET,
2051                                                         ObjectIdGetDatum(srctype),
2052                                                         ObjectIdGetDatum(targettype));
2053         if (!HeapTupleIsValid(tuple))
2054                 return false;                   /* no cast */
2055         castForm = (Form_pg_cast) GETSTRUCT(tuple);
2056
2057         result = (castForm->castmethod == COERCION_METHOD_BINARY &&
2058                           castForm->castcontext == COERCION_CODE_IMPLICIT);
2059
2060         ReleaseSysCache(tuple);
2061
2062         return result;
2063 }
2064
2065
2066 /*
2067  * find_coercion_pathway
2068  *              Look for a coercion pathway between two types.
2069  *
2070  * Currently, this deals only with scalar-type cases; it does not consider
2071  * polymorphic types nor casts between composite types.  (Perhaps fold
2072  * those in someday?)
2073  *
2074  * ccontext determines the set of available casts.
2075  *
2076  * The possible result codes are:
2077  *      COERCION_PATH_NONE: failed to find any coercion pathway
2078  *                              *funcid is set to InvalidOid
2079  *      COERCION_PATH_FUNC: apply the coercion function returned in *funcid
2080  *      COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
2081  *                              *funcid is set to InvalidOid
2082  *      COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
2083  *                              *funcid is set to the element cast function, or InvalidOid
2084  *                              if the array elements are binary-compatible
2085  *      COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
2086  *                              *funcid is set to InvalidOid
2087  *
2088  * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
2089  * needed to do the coercion; if the target is a domain then we may need to
2090  * apply domain constraint checking.  If you want to check for a zero-effort
2091  * conversion then use IsBinaryCoercible().
2092  */
2093 CoercionPathType
2094 find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
2095                                           CoercionContext ccontext,
2096                                           Oid *funcid)
2097 {
2098         CoercionPathType result = COERCION_PATH_NONE;
2099         HeapTuple       tuple;
2100
2101         *funcid = InvalidOid;
2102
2103         /* Perhaps the types are domains; if so, look at their base types */
2104         if (OidIsValid(sourceTypeId))
2105                 sourceTypeId = getBaseType(sourceTypeId);
2106         if (OidIsValid(targetTypeId))
2107                 targetTypeId = getBaseType(targetTypeId);
2108
2109         /* Domains are always coercible to and from their base type */
2110         if (sourceTypeId == targetTypeId)
2111                 return COERCION_PATH_RELABELTYPE;
2112
2113         /* Look in pg_cast */
2114         tuple = SearchSysCache2(CASTSOURCETARGET,
2115                                                         ObjectIdGetDatum(sourceTypeId),
2116                                                         ObjectIdGetDatum(targetTypeId));
2117
2118         if (HeapTupleIsValid(tuple))
2119         {
2120                 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2121                 CoercionContext castcontext;
2122
2123                 /* convert char value for castcontext to CoercionContext enum */
2124                 switch (castForm->castcontext)
2125                 {
2126                         case COERCION_CODE_IMPLICIT:
2127                                 castcontext = COERCION_IMPLICIT;
2128                                 break;
2129                         case COERCION_CODE_ASSIGNMENT:
2130                                 castcontext = COERCION_ASSIGNMENT;
2131                                 break;
2132                         case COERCION_CODE_EXPLICIT:
2133                                 castcontext = COERCION_EXPLICIT;
2134                                 break;
2135                         default:
2136                                 elog(ERROR, "unrecognized castcontext: %d",
2137                                          (int) castForm->castcontext);
2138                                 castcontext = 0;        /* keep compiler quiet */
2139                                 break;
2140                 }
2141
2142                 /* Rely on ordering of enum for correct behavior here */
2143                 if (ccontext >= castcontext)
2144                 {
2145                         switch (castForm->castmethod)
2146                         {
2147                                 case COERCION_METHOD_FUNCTION:
2148                                         result = COERCION_PATH_FUNC;
2149                                         *funcid = castForm->castfunc;
2150                                         break;
2151                                 case COERCION_METHOD_INOUT:
2152                                         result = COERCION_PATH_COERCEVIAIO;
2153                                         break;
2154                                 case COERCION_METHOD_BINARY:
2155                                         result = COERCION_PATH_RELABELTYPE;
2156                                         break;
2157                                 default:
2158                                         elog(ERROR, "unrecognized castmethod: %d",
2159                                                  (int) castForm->castmethod);
2160                                         break;
2161                         }
2162                 }
2163
2164                 ReleaseSysCache(tuple);
2165         }
2166         else
2167         {
2168                 /*
2169                  * If there's no pg_cast entry, perhaps we are dealing with a pair of
2170                  * array types.  If so, and if the element types have a suitable cast,
2171                  * report that we can coerce with an ArrayCoerceExpr.
2172                  *
2173                  * Note that the source type can be a domain over array, but not the
2174                  * target, because ArrayCoerceExpr won't check domain constraints.
2175                  *
2176                  * Hack: disallow coercions to oidvector and int2vector, which
2177                  * otherwise tend to capture coercions that should go to "real" array
2178                  * types.  We want those types to be considered "real" arrays for many
2179                  * purposes, but not this one.  (Also, ArrayCoerceExpr isn't
2180                  * guaranteed to produce an output that meets the restrictions of
2181                  * these datatypes, such as being 1-dimensional.)
2182                  */
2183                 if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
2184                 {
2185                         Oid                     targetElem;
2186                         Oid                     sourceElem;
2187
2188                         if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
2189                         (sourceElem = get_base_element_type(sourceTypeId)) != InvalidOid)
2190                         {
2191                                 CoercionPathType elempathtype;
2192                                 Oid                     elemfuncid;
2193
2194                                 elempathtype = find_coercion_pathway(targetElem,
2195                                                                                                          sourceElem,
2196                                                                                                          ccontext,
2197                                                                                                          &elemfuncid);
2198                                 if (elempathtype != COERCION_PATH_NONE &&
2199                                         elempathtype != COERCION_PATH_ARRAYCOERCE)
2200                                 {
2201                                         *funcid = elemfuncid;
2202                                         if (elempathtype == COERCION_PATH_COERCEVIAIO)
2203                                                 result = COERCION_PATH_COERCEVIAIO;
2204                                         else
2205                                                 result = COERCION_PATH_ARRAYCOERCE;
2206                                 }
2207                         }
2208                 }
2209
2210                 /*
2211                  * If we still haven't found a possibility, consider automatic casting
2212                  * using I/O functions.  We allow assignment casts to string types and
2213                  * explicit casts from string types to be handled this way. (The
2214                  * CoerceViaIO mechanism is a lot more general than that, but this is
2215                  * all we want to allow in the absence of a pg_cast entry.) It would
2216                  * probably be better to insist on explicit casts in both directions,
2217                  * but this is a compromise to preserve something of the pre-8.3
2218                  * behavior that many types had implicit (yipes!) casts to text.
2219                  */
2220                 if (result == COERCION_PATH_NONE)
2221                 {
2222                         if (ccontext >= COERCION_ASSIGNMENT &&
2223                                 TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
2224                                 result = COERCION_PATH_COERCEVIAIO;
2225                         else if (ccontext >= COERCION_EXPLICIT &&
2226                                          TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
2227                                 result = COERCION_PATH_COERCEVIAIO;
2228                 }
2229         }
2230
2231         return result;
2232 }
2233
2234
2235 /*
2236  * find_typmod_coercion_function -- does the given type need length coercion?
2237  *
2238  * If the target type possesses a pg_cast function from itself to itself,
2239  * it must need length coercion.
2240  *
2241  * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
2242  *
2243  * If the given type is a varlena array type, we do not look for a coercion
2244  * function associated directly with the array type, but instead look for
2245  * one associated with the element type.  An ArrayCoerceExpr node must be
2246  * used to apply such a function.
2247  *
2248  * We use the same result enum as find_coercion_pathway, but the only possible
2249  * result codes are:
2250  *      COERCION_PATH_NONE: no length coercion needed
2251  *      COERCION_PATH_FUNC: apply the function returned in *funcid
2252  *      COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
2253  */
2254 CoercionPathType
2255 find_typmod_coercion_function(Oid typeId,
2256                                                           Oid *funcid)
2257 {
2258         CoercionPathType result;
2259         Type            targetType;
2260         Form_pg_type typeForm;
2261         HeapTuple       tuple;
2262
2263         *funcid = InvalidOid;
2264         result = COERCION_PATH_FUNC;
2265
2266         targetType = typeidType(typeId);
2267         typeForm = (Form_pg_type) GETSTRUCT(targetType);
2268
2269         /* Check for a varlena array type */
2270         if (typeForm->typelem != InvalidOid && typeForm->typlen == -1)
2271         {
2272                 /* Yes, switch our attention to the element type */
2273                 typeId = typeForm->typelem;
2274                 result = COERCION_PATH_ARRAYCOERCE;
2275         }
2276         ReleaseSysCache(targetType);
2277
2278         /* Look in pg_cast */
2279         tuple = SearchSysCache2(CASTSOURCETARGET,
2280                                                         ObjectIdGetDatum(typeId),
2281                                                         ObjectIdGetDatum(typeId));
2282
2283         if (HeapTupleIsValid(tuple))
2284         {
2285                 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
2286
2287                 *funcid = castForm->castfunc;
2288                 ReleaseSysCache(tuple);
2289         }
2290
2291         if (!OidIsValid(*funcid))
2292                 result = COERCION_PATH_NONE;
2293
2294         return result;
2295 }
2296
2297 /*
2298  * is_complex_array
2299  *              Is this type an array of composite?
2300  *
2301  * Note: this will not return true for record[]; check for RECORDARRAYOID
2302  * separately if needed.
2303  */
2304 static bool
2305 is_complex_array(Oid typid)
2306 {
2307         Oid                     elemtype = get_element_type(typid);
2308
2309         return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));
2310 }
2311
2312
2313 /*
2314  * Check whether reltypeId is the row type of a typed table of type
2315  * reloftypeId.  (This is conceptually similar to the subtype
2316  * relationship checked by typeInheritsFrom().)
2317  */
2318 static bool
2319 typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
2320 {
2321         Oid                     relid = typeidTypeRelid(reltypeId);
2322         bool            result = false;
2323
2324         if (relid)
2325         {
2326                 HeapTuple       tp;
2327                 Form_pg_class reltup;
2328
2329                 tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2330                 if (!HeapTupleIsValid(tp))
2331                         elog(ERROR, "cache lookup failed for relation %u", relid);
2332
2333                 reltup = (Form_pg_class) GETSTRUCT(tp);
2334                 if (reltup->reloftype == reloftypeId)
2335                         result = true;
2336
2337                 ReleaseSysCache(tp);
2338         }
2339
2340         return result;
2341 }