Coverage Report

Created: 2026-11-12 07:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/postgres/src/backend/parser/parse_coerce.c
Line
Count
Source
1
/*-------------------------------------------------------------------------
2
 *
3
 * parse_coerce.c
4
 *    handle type coercions/conversions for parser
5
 *
6
 * Portions Copyright (c) 1996-2026, 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 "access/htup_details.h"
18
#include "catalog/pg_cast.h"
19
#include "catalog/pg_class.h"
20
#include "catalog/pg_inherits.h"
21
#include "catalog/pg_proc.h"
22
#include "catalog/pg_type.h"
23
#include "nodes/makefuncs.h"
24
#include "nodes/nodeFuncs.h"
25
#include "parser/parse_coerce.h"
26
#include "parser/parse_relation.h"
27
#include "parser/parse_type.h"
28
#include "utils/builtins.h"
29
#include "utils/datum.h"    /* needed for datumIsEqual() */
30
#include "utils/fmgroids.h"
31
#include "utils/lsyscache.h"
32
#include "utils/syscache.h"
33
#include "utils/typcache.h"
34
35
36
static Node *coerce_type_typmod(Node *node,
37
                Oid targetTypeId, int32 targetTypMod,
38
                CoercionContext ccontext, CoercionForm cformat,
39
                int location,
40
                bool hideInputCoercion);
41
static void hide_coercion_node(Node *node);
42
static Node *build_coercion_expression(Node *node,
43
                     CoercionPathType pathtype,
44
                     Oid funcId,
45
                     Oid targetTypeId, int32 targetTypMod,
46
                     CoercionContext ccontext, CoercionForm cformat,
47
                     int location);
48
static Node *coerce_record_to_complex(ParseState *pstate, Node *node,
49
                    Oid targetTypeId,
50
                    CoercionContext ccontext,
51
                    CoercionForm cformat,
52
                    int location);
53
static bool is_complex_array(Oid typid);
54
static bool typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId);
55
56
57
/*
58
 * coerce_to_target_type()
59
 *    Convert an expression to a target type and typmod.
60
 *
61
 * This is the general-purpose entry point for arbitrary type coercion
62
 * operations.  Direct use of the component operations can_coerce_type,
63
 * coerce_type, and coerce_type_typmod should be restricted to special
64
 * cases (eg, when the conversion is expected to succeed).
65
 *
66
 * Returns the possibly-transformed expression tree, or NULL if the type
67
 * conversion is not possible.  (We do this, rather than ereport'ing directly,
68
 * so that callers can generate custom error messages indicating context.)
69
 *
70
 * pstate - parse state (can be NULL, see coerce_type)
71
 * expr - input expression tree (already transformed by transformExpr)
72
 * exprtype - result type of expr
73
 * targettype - desired result type
74
 * targettypmod - desired result typmod
75
 * ccontext, cformat - context indicators to control coercions
76
 * location - parse location of the coercion request, or -1 if unknown/implicit
77
 */
78
Node *
79
coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype,
80
            Oid targettype, int32 targettypmod,
81
            CoercionContext ccontext,
82
            CoercionForm cformat,
83
            int location)
84
0
{
85
0
  Node     *result;
86
0
  Node     *origexpr;
87
88
0
  if (!can_coerce_type(1, &exprtype, &targettype, ccontext))
89
0
    return NULL;
90
91
  /*
92
   * If the input has a CollateExpr at the top, strip it off, perform the
93
   * coercion, and put a new one back on.  This is annoying since it
94
   * duplicates logic in coerce_type, but if we don't do this then it's too
95
   * hard to tell whether coerce_type actually changed anything, and we
96
   * *must* know that to avoid possibly calling hide_coercion_node on
97
   * something that wasn't generated by coerce_type.  Note that if there are
98
   * multiple stacked CollateExprs, we just discard all but the topmost.
99
   * Also, if the target type isn't collatable, we discard the CollateExpr.
100
   */
101
0
  origexpr = expr;
102
0
  while (expr && IsA(expr, CollateExpr))
103
0
    expr = (Node *) ((CollateExpr *) expr)->arg;
104
105
0
  result = coerce_type(pstate, expr, exprtype,
106
0
             targettype, targettypmod,
107
0
             ccontext, cformat, location);
108
109
  /*
110
   * If the target is a fixed-length type, it may need a length coercion as
111
   * well as a type coercion.  If we find ourselves adding both, force the
112
   * inner coercion node to implicit display form.
113
   */
114
0
  result = coerce_type_typmod(result,
115
0
                targettype, targettypmod,
116
0
                ccontext, cformat, location,
117
0
                (result != expr && !IsA(result, Const)));
118
119
0
  if (expr != origexpr && type_is_collatable(targettype))
120
0
  {
121
    /* Reinstall top CollateExpr */
122
0
    CollateExpr *coll = (CollateExpr *) origexpr;
123
0
    CollateExpr *newcoll = makeNode(CollateExpr);
124
125
0
    newcoll->arg = (Expr *) result;
126
0
    newcoll->collOid = coll->collOid;
127
0
    newcoll->location = coll->location;
128
0
    result = (Node *) newcoll;
129
0
  }
130
131
0
  return result;
132
0
}
133
134
135
/*
136
 * coerce_type()
137
 *    Convert an expression to a different type.
138
 *
139
 * The caller should already have determined that the coercion is possible;
140
 * see can_coerce_type.
141
 *
142
 * Normally, no coercion to a typmod (length) is performed here.  The caller
143
 * must call coerce_type_typmod as well, if a typmod constraint is wanted.
144
 * (But if the target type is a domain, it may internally contain a
145
 * typmod constraint, which will be applied inside coerce_to_domain.)
146
 * In some cases pg_cast specifies a type coercion function that also
147
 * applies length conversion, and in those cases only, the result will
148
 * already be properly coerced to the specified typmod.
149
 *
150
 * pstate is only used in the case that we are able to resolve the type of
151
 * a previously UNKNOWN Param.  It is okay to pass pstate = NULL if the
152
 * caller does not want type information updated for Params.
153
 *
154
 * Note: this function must not modify the given expression tree, only add
155
 * decoration on top of it.  See transformSetOperationTree, for example.
156
 */
157
Node *
158
coerce_type(ParseState *pstate, Node *node,
159
      Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod,
160
      CoercionContext ccontext, CoercionForm cformat, int location)
161
0
{
162
0
  Node     *result;
163
0
  CoercionPathType pathtype;
164
0
  Oid     funcId;
165
166
0
  if (targetTypeId == inputTypeId ||
167
0
    node == NULL)
168
0
  {
169
    /* no conversion needed */
170
0
    return node;
171
0
  }
172
0
  if (targetTypeId == ANYOID ||
173
0
    targetTypeId == ANYELEMENTOID ||
174
0
    targetTypeId == ANYNONARRAYOID ||
175
0
    targetTypeId == ANYCOMPATIBLEOID ||
176
0
    targetTypeId == ANYCOMPATIBLENONARRAYOID)
177
0
  {
178
    /*
179
     * Assume can_coerce_type verified that implicit coercion is okay.
180
     *
181
     * Note: by returning the unmodified node here, we are saying that
182
     * it's OK to treat an UNKNOWN constant as a valid input for a
183
     * function accepting one of these pseudotypes.  This should be all
184
     * right, since an UNKNOWN value is still a perfectly valid Datum.
185
     *
186
     * NB: we do NOT want a RelabelType here: the exposed type of the
187
     * function argument must be its actual type, not the polymorphic
188
     * pseudotype.
189
     */
190
0
    return node;
191
0
  }
192
0
  if (targetTypeId == ANYARRAYOID ||
193
0
    targetTypeId == ANYENUMOID ||
194
0
    targetTypeId == ANYRANGEOID ||
195
0
    targetTypeId == ANYMULTIRANGEOID ||
196
0
    targetTypeId == ANYCOMPATIBLEARRAYOID ||
197
0
    targetTypeId == ANYCOMPATIBLERANGEOID ||
198
0
    targetTypeId == ANYCOMPATIBLEMULTIRANGEOID)
199
0
  {
200
    /*
201
     * Assume can_coerce_type verified that implicit coercion is okay.
202
     *
203
     * These cases are unlike the ones above because the exposed type of
204
     * the argument must be an actual array, enum, range, or multirange
205
     * type.  In particular the argument must *not* be an UNKNOWN
206
     * constant.  If it is, we just fall through; below, we'll call the
207
     * pseudotype's input function, which will produce an error.  Also, if
208
     * what we have is a domain over array, enum, range, or multirange, we
209
     * have to relabel it to its base type.
210
     *
211
     * Note: currently, we can't actually see a domain-over-enum here,
212
     * since the other functions in this file will not match such a
213
     * parameter to ANYENUM.  But that should get changed eventually.
214
     */
215
0
    if (inputTypeId != UNKNOWNOID)
216
0
    {
217
0
      Oid     baseTypeId = getBaseType(inputTypeId);
218
219
0
      if (baseTypeId != inputTypeId)
220
0
      {
221
0
        RelabelType *r = makeRelabelType((Expr *) node,
222
0
                         baseTypeId, -1,
223
0
                         InvalidOid,
224
0
                         cformat);
225
226
0
        r->location = location;
227
0
        return (Node *) r;
228
0
      }
229
      /* Not a domain type, so return it as-is */
230
0
      return node;
231
0
    }
232
0
  }
233
0
  if (inputTypeId == UNKNOWNOID && IsA(node, Const))
234
0
  {
235
    /*
236
     * Input is a string constant with previously undetermined type. Apply
237
     * the target type's typinput function to it to produce a constant of
238
     * the target type.
239
     *
240
     * NOTE: this case cannot be folded together with the other
241
     * constant-input case, since the typinput function does not
242
     * necessarily behave the same as a type conversion function. For
243
     * example, int4's typinput function will reject "1.2", whereas
244
     * float-to-int type conversion will round to integer.
245
     *
246
     * XXX if the typinput function is not immutable, we really ought to
247
     * postpone evaluation of the function call until runtime. But there
248
     * is no way to represent a typinput function call as an expression
249
     * tree, because C-string values are not Datums. (XXX This *is*
250
     * possible as of 7.3, do we want to do it?)
251
     */
252
0
    Const    *con = (Const *) node;
253
0
    Const    *newcon = makeNode(Const);
254
0
    Oid     baseTypeId;
255
0
    int32   baseTypeMod;
256
0
    int32   inputTypeMod;
257
0
    Type    baseType;
258
0
    ParseCallbackState pcbstate;
259
260
    /*
261
     * If the target type is a domain, we want to call its base type's
262
     * input routine, not domain_in().  This is to avoid premature failure
263
     * when the domain applies a typmod: existing input routines follow
264
     * implicit-coercion semantics for length checks, which is not always
265
     * what we want here.  The needed check will be applied properly
266
     * inside coerce_to_domain().
267
     */
268
0
    baseTypeMod = targetTypeMod;
269
0
    baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
270
271
    /*
272
     * For most types we pass typmod -1 to the input routine, because
273
     * existing input routines follow implicit-coercion semantics for
274
     * length checks, which is not always what we want here.  Any length
275
     * constraint will be applied later by our caller.  An exception
276
     * however is the INTERVAL type, for which we *must* pass the typmod
277
     * or it won't be able to obey the bizarre SQL-spec input rules. (Ugly
278
     * as sin, but so is this part of the spec...)
279
     */
280
0
    if (baseTypeId == INTERVALOID)
281
0
      inputTypeMod = baseTypeMod;
282
0
    else
283
0
      inputTypeMod = -1;
284
285
0
    baseType = typeidType(baseTypeId);
286
287
0
    newcon->consttype = baseTypeId;
288
0
    newcon->consttypmod = inputTypeMod;
289
0
    newcon->constcollid = typeTypeCollation(baseType);
290
0
    newcon->constlen = typeLen(baseType);
291
0
    newcon->constbyval = typeByVal(baseType);
292
0
    newcon->constisnull = con->constisnull;
293
294
    /*
295
     * We use the original literal's location regardless of the position
296
     * of the coercion.  This is a change from pre-9.2 behavior, meant to
297
     * simplify life for pg_stat_statements.
298
     */
299
0
    newcon->location = con->location;
300
301
    /*
302
     * Set up to point at the constant's text if the input routine throws
303
     * an error.
304
     */
305
0
    setup_parser_errposition_callback(&pcbstate, pstate, con->location);
306
307
    /*
308
     * We assume here that UNKNOWN's internal representation is the same
309
     * as CSTRING.
310
     */
311
0
    if (!con->constisnull)
312
0
      newcon->constvalue = stringTypeDatum(baseType,
313
0
                         DatumGetCString(con->constvalue),
314
0
                         inputTypeMod);
315
0
    else
316
0
      newcon->constvalue = stringTypeDatum(baseType,
317
0
                         NULL,
318
0
                         inputTypeMod);
319
320
    /*
321
     * If it's a varlena value, force it to be in non-expanded
322
     * (non-toasted) format; this avoids any possible dependency on
323
     * external values and improves consistency of representation.
324
     */
325
0
    if (!con->constisnull && newcon->constlen == -1)
326
0
      newcon->constvalue =
327
0
        PointerGetDatum(PG_DETOAST_DATUM(newcon->constvalue));
328
329
#ifdef RANDOMIZE_ALLOCATED_MEMORY
330
331
    /*
332
     * For pass-by-reference data types, repeat the conversion to see if
333
     * the input function leaves any uninitialized bytes in the result. We
334
     * can only detect that reliably if RANDOMIZE_ALLOCATED_MEMORY is
335
     * enabled, so we don't bother testing otherwise.  The reason we don't
336
     * want any instability in the input function is that comparison of
337
     * Const nodes relies on bytewise comparison of the datums, so if the
338
     * input function leaves garbage then subexpressions that should be
339
     * identical may not get recognized as such.  See pgsql-hackers
340
     * discussion of 2008-04-04.
341
     */
342
    if (!con->constisnull && !newcon->constbyval)
343
    {
344
      Datum   val2;
345
346
      val2 = stringTypeDatum(baseType,
347
                   DatumGetCString(con->constvalue),
348
                   inputTypeMod);
349
      if (newcon->constlen == -1)
350
        val2 = PointerGetDatum(PG_DETOAST_DATUM(val2));
351
      if (!datumIsEqual(newcon->constvalue, val2, false, newcon->constlen))
352
        elog(WARNING, "type %s has unstable input conversion for \"%s\"",
353
           typeTypeName(baseType), DatumGetCString(con->constvalue));
354
    }
355
#endif
356
357
0
    cancel_parser_errposition_callback(&pcbstate);
358
359
0
    result = (Node *) newcon;
360
361
    /* If target is a domain, apply constraints. */
362
0
    if (baseTypeId != targetTypeId)
363
0
      result = coerce_to_domain(result,
364
0
                    baseTypeId, baseTypeMod,
365
0
                    targetTypeId,
366
0
                    ccontext, cformat, location,
367
0
                    false);
368
369
0
    ReleaseSysCache(baseType);
370
371
0
    return result;
372
0
  }
373
0
  if (IsA(node, Param) &&
374
0
    pstate != NULL && pstate->p_coerce_param_hook != NULL)
375
0
  {
376
    /*
377
     * Allow the CoerceParamHook to decide what happens.  It can return a
378
     * transformed node (very possibly the same Param node), or return
379
     * NULL to indicate we should proceed with normal coercion.
380
     */
381
0
    result = pstate->p_coerce_param_hook(pstate,
382
0
                       (Param *) node,
383
0
                       targetTypeId,
384
0
                       targetTypeMod,
385
0
                       location);
386
0
    if (result)
387
0
      return result;
388
0
  }
389
0
  if (IsA(node, CollateExpr))
390
0
  {
391
    /*
392
     * If we have a COLLATE clause, we have to push the coercion
393
     * underneath the COLLATE; or discard the COLLATE if the target type
394
     * isn't collatable.  This is really ugly, but there is little choice
395
     * because the above hacks on Consts and Params wouldn't happen
396
     * otherwise.  This kluge has consequences in coerce_to_target_type.
397
     */
398
0
    CollateExpr *coll = (CollateExpr *) node;
399
400
0
    result = coerce_type(pstate, (Node *) coll->arg,
401
0
               inputTypeId, targetTypeId, targetTypeMod,
402
0
               ccontext, cformat, location);
403
0
    if (type_is_collatable(targetTypeId))
404
0
    {
405
0
      CollateExpr *newcoll = makeNode(CollateExpr);
406
407
0
      newcoll->arg = (Expr *) result;
408
0
      newcoll->collOid = coll->collOid;
409
0
      newcoll->location = coll->location;
410
0
      result = (Node *) newcoll;
411
0
    }
412
0
    return result;
413
0
  }
414
0
  pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
415
0
                   &funcId);
416
0
  if (pathtype != COERCION_PATH_NONE)
417
0
  {
418
0
    Oid     baseTypeId;
419
0
    int32   baseTypeMod;
420
421
0
    baseTypeMod = targetTypeMod;
422
0
    baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
423
424
0
    if (pathtype != COERCION_PATH_RELABELTYPE)
425
0
    {
426
      /*
427
       * Generate an expression tree representing run-time application
428
       * of the conversion function.  If we are dealing with a domain
429
       * target type, the conversion function will yield the base type,
430
       * and we need to extract the correct typmod to use from the
431
       * domain's typtypmod.
432
       */
433
0
      result = build_coercion_expression(node, pathtype, funcId,
434
0
                         baseTypeId, baseTypeMod,
435
0
                         ccontext, cformat, location);
436
437
      /*
438
       * If domain, coerce to the domain type and relabel with domain
439
       * type ID, hiding the previous coercion node.
440
       */
441
0
      if (targetTypeId != baseTypeId)
442
0
        result = coerce_to_domain(result, baseTypeId, baseTypeMod,
443
0
                      targetTypeId,
444
0
                      ccontext, cformat, location,
445
0
                      true);
446
0
    }
447
0
    else
448
0
    {
449
      /*
450
       * We don't need to do a physical conversion, but we do need to
451
       * attach a RelabelType node so that the expression will be seen
452
       * to have the intended type when inspected by higher-level code.
453
       *
454
       * Also, domains may have value restrictions beyond the base type
455
       * that must be accounted for.  If the destination is a domain
456
       * then we won't need a RelabelType node.
457
       */
458
0
      result = coerce_to_domain(node, baseTypeId, baseTypeMod,
459
0
                    targetTypeId,
460
0
                    ccontext, cformat, location,
461
0
                    false);
462
0
      if (result == node)
463
0
      {
464
        /*
465
         * XXX could we label result with exprTypmod(node) instead of
466
         * default -1 typmod, to save a possible length-coercion
467
         * later? Would work if both types have same interpretation of
468
         * typmod, which is likely but not certain.
469
         */
470
0
        RelabelType *r = makeRelabelType((Expr *) result,
471
0
                         targetTypeId, -1,
472
0
                         InvalidOid,
473
0
                         cformat);
474
475
0
        r->location = location;
476
0
        result = (Node *) r;
477
0
      }
478
0
    }
479
0
    return result;
480
0
  }
481
0
  if (inputTypeId == RECORDOID &&
482
0
    ISCOMPLEX(targetTypeId))
483
0
  {
484
    /* Coerce a RECORD to a specific complex type */
485
0
    return coerce_record_to_complex(pstate, node, targetTypeId,
486
0
                    ccontext, cformat, location);
487
0
  }
488
0
  if (targetTypeId == RECORDOID &&
489
0
    ISCOMPLEX(inputTypeId))
490
0
  {
491
    /* Coerce a specific complex type to RECORD */
492
    /* NB: we do NOT want a RelabelType here */
493
0
    return node;
494
0
  }
495
#ifdef NOT_USED
496
  if (inputTypeId == RECORDARRAYOID &&
497
    is_complex_array(targetTypeId))
498
  {
499
    /* Coerce record[] to a specific complex array type */
500
    /* not implemented yet ... */
501
  }
502
#endif
503
0
  if (targetTypeId == RECORDARRAYOID &&
504
0
    is_complex_array(inputTypeId))
505
0
  {
506
    /* Coerce a specific complex array type to record[] */
507
    /* NB: we do NOT want a RelabelType here */
508
0
    return node;
509
0
  }
510
0
  if (typeInheritsFrom(inputTypeId, targetTypeId)
511
0
    || typeIsOfTypedTable(inputTypeId, targetTypeId))
512
0
  {
513
    /*
514
     * Input class type is a subclass of target, so generate an
515
     * appropriate runtime conversion (removing unneeded columns and
516
     * possibly rearranging the ones that are wanted).
517
     *
518
     * We will also get here when the input is a domain over a subclass of
519
     * the target type.  To keep life simple for the executor, we define
520
     * ConvertRowtypeExpr as only working between regular composite types;
521
     * therefore, in such cases insert a RelabelType to smash the input
522
     * expression down to its base type.
523
     */
524
0
    Oid     baseTypeId = getBaseType(inputTypeId);
525
0
    ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
526
527
0
    if (baseTypeId != inputTypeId)
528
0
    {
529
0
      RelabelType *rt = makeRelabelType((Expr *) node,
530
0
                        baseTypeId, -1,
531
0
                        InvalidOid,
532
0
                        COERCE_IMPLICIT_CAST);
533
534
0
      rt->location = location;
535
0
      node = (Node *) rt;
536
0
    }
537
0
    r->arg = (Expr *) node;
538
0
    r->resulttype = targetTypeId;
539
0
    r->convertformat = cformat;
540
0
    r->location = location;
541
0
    return (Node *) r;
542
0
  }
543
  /* If we get here, caller blew it */
544
0
  elog(ERROR, "failed to find conversion function from %s to %s",
545
0
     format_type_be(inputTypeId), format_type_be(targetTypeId));
546
0
  return NULL;       /* keep compiler quiet */
547
0
}
548
549
550
/*
551
 * can_coerce_type()
552
 *    Can input_typeids be coerced to target_typeids?
553
 *
554
 * We must be told the context (CAST construct, assignment, implicit coercion)
555
 * as this determines the set of available casts.
556
 */
557
bool
558
can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids,
559
        CoercionContext ccontext)
560
0
{
561
0
  bool    have_generics = false;
562
0
  int     i;
563
564
  /* run through argument list... */
565
0
  for (i = 0; i < nargs; i++)
566
0
  {
567
0
    Oid     inputTypeId = input_typeids[i];
568
0
    Oid     targetTypeId = target_typeids[i];
569
0
    CoercionPathType pathtype;
570
0
    Oid     funcId;
571
572
    /* no problem if same type */
573
0
    if (inputTypeId == targetTypeId)
574
0
      continue;
575
576
    /* reject all cases of casting something else to/from "internal" */
577
0
    if (inputTypeId == INTERNALOID || targetTypeId == INTERNALOID)
578
0
      return false;
579
580
    /* accept if target is ANY */
581
0
    if (targetTypeId == ANYOID)
582
0
      continue;
583
584
    /* accept if target is polymorphic, for now */
585
0
    if (IsPolymorphicType(targetTypeId))
586
0
    {
587
0
      have_generics = true; /* do more checking later */
588
0
      continue;
589
0
    }
590
591
    /*
592
     * If input is an untyped string constant, assume we can convert it to
593
     * anything.
594
     */
595
0
    if (inputTypeId == UNKNOWNOID)
596
0
      continue;
597
598
    /*
599
     * If pg_cast shows that we can coerce, accept.  This test now covers
600
     * both binary-compatible and coercion-function cases.
601
     */
602
0
    pathtype = find_coercion_pathway(targetTypeId, inputTypeId, ccontext,
603
0
                     &funcId);
604
0
    if (pathtype != COERCION_PATH_NONE)
605
0
      continue;
606
607
    /*
608
     * If input is RECORD and target is a composite type, assume we can
609
     * coerce (may need tighter checking here)
610
     */
611
0
    if (inputTypeId == RECORDOID &&
612
0
      ISCOMPLEX(targetTypeId))
613
0
      continue;
614
615
    /*
616
     * If input is a composite type and target is RECORD, accept
617
     */
618
0
    if (targetTypeId == RECORDOID &&
619
0
      ISCOMPLEX(inputTypeId))
620
0
      continue;
621
622
#ifdef NOT_USED         /* not implemented yet */
623
624
    /*
625
     * If input is record[] and target is a composite array type, assume
626
     * we can coerce (may need tighter checking here)
627
     */
628
    if (inputTypeId == RECORDARRAYOID &&
629
      is_complex_array(targetTypeId))
630
      continue;
631
#endif
632
633
    /*
634
     * If input is a composite array type and target is record[], accept
635
     */
636
0
    if (targetTypeId == RECORDARRAYOID &&
637
0
      is_complex_array(inputTypeId))
638
0
      continue;
639
640
    /*
641
     * If input is a class type that inherits from target, accept
642
     */
643
0
    if (typeInheritsFrom(inputTypeId, targetTypeId)
644
0
      || typeIsOfTypedTable(inputTypeId, targetTypeId))
645
0
      continue;
646
647
    /*
648
     * Else, cannot coerce at this argument position
649
     */
650
0
    return false;
651
0
  }
652
653
  /* If we found any generic argument types, cross-check them */
654
0
  if (have_generics)
655
0
  {
656
0
    if (!check_generic_type_consistency(input_typeids, target_typeids,
657
0
                      nargs))
658
0
      return false;
659
0
  }
660
661
0
  return true;
662
0
}
663
664
665
/*
666
 * Create an expression tree to represent coercion to a domain type.
667
 *
668
 * 'arg': input expression
669
 * 'baseTypeId': base type of domain
670
 * 'baseTypeMod': base type typmod of domain
671
 * 'typeId': target type to coerce to
672
 * 'ccontext': context indicator to control coercions
673
 * 'cformat': coercion display format
674
 * 'location': coercion request location
675
 * 'hideInputCoercion': if true, hide the input coercion under this one.
676
 *
677
 * If the target type isn't a domain, the given 'arg' is returned as-is.
678
 */
679
Node *
680
coerce_to_domain(Node *arg, Oid baseTypeId, int32 baseTypeMod, Oid typeId,
681
         CoercionContext ccontext, CoercionForm cformat, int location,
682
         bool hideInputCoercion)
683
0
{
684
0
  CoerceToDomain *result;
685
686
  /* We now require the caller to supply correct baseTypeId/baseTypeMod */
687
0
  Assert(OidIsValid(baseTypeId));
688
689
  /* If it isn't a domain, return the node as it was passed in */
690
0
  if (baseTypeId == typeId)
691
0
    return arg;
692
693
  /* Suppress display of nested coercion steps */
694
0
  if (hideInputCoercion)
695
0
    hide_coercion_node(arg);
696
697
  /*
698
   * If the domain applies a typmod to its base type, build the appropriate
699
   * coercion step.  Mark it implicit for display purposes, because we don't
700
   * want it shown separately by ruleutils.c; but the isExplicit flag passed
701
   * to the conversion function depends on the manner in which the domain
702
   * coercion is invoked, so that the semantics of implicit and explicit
703
   * coercion differ.  (Is that really the behavior we want?)
704
   *
705
   * NOTE: because we apply this as part of the fixed expression structure,
706
   * ALTER DOMAIN cannot alter the typtypmod.  But it's unclear that that
707
   * would be safe to do anyway, without lots of knowledge about what the
708
   * base type thinks the typmod means.
709
   */
710
0
  arg = coerce_type_typmod(arg, baseTypeId, baseTypeMod,
711
0
               ccontext, COERCE_IMPLICIT_CAST, location,
712
0
               false);
713
714
  /*
715
   * Now build the domain coercion node.  This represents run-time checking
716
   * of any constraints currently attached to the domain.  This also ensures
717
   * that the expression is properly labeled as to result type.
718
   */
719
0
  result = makeNode(CoerceToDomain);
720
0
  result->arg = (Expr *) arg;
721
0
  result->resulttype = typeId;
722
0
  result->resulttypmod = -1;  /* currently, always -1 for domains */
723
  /* resultcollid will be set by parse_collate.c */
724
0
  result->coercionformat = cformat;
725
0
  result->location = location;
726
727
0
  return (Node *) result;
728
0
}
729
730
731
/*
732
 * coerce_type_typmod()
733
 *    Force a value to a particular typmod, if meaningful and possible.
734
 *
735
 * This is applied to values that are going to be stored in a relation
736
 * (where we have an atttypmod for the column) as well as values being
737
 * explicitly CASTed (where the typmod comes from the target type spec).
738
 *
739
 * The caller must have already ensured that the value is of the correct
740
 * type, typically by applying coerce_type.
741
 *
742
 * ccontext may affect semantics, depending on whether the length coercion
743
 * function pays attention to the isExplicit flag it's passed.
744
 *
745
 * cformat determines the display properties of the generated node (if any).
746
 *
747
 * If hideInputCoercion is true *and* we generate a node, the input node is
748
 * forced to IMPLICIT display form, so that only the typmod coercion node will
749
 * be visible when displaying the expression.
750
 *
751
 * NOTE: this does not need to work on domain types, because any typmod
752
 * coercion for a domain is considered to be part of the type coercion
753
 * needed to produce the domain value in the first place.  So, no getBaseType.
754
 */
755
static Node *
756
coerce_type_typmod(Node *node, Oid targetTypeId, int32 targetTypMod,
757
           CoercionContext ccontext, CoercionForm cformat,
758
           int location,
759
           bool hideInputCoercion)
760
0
{
761
0
  CoercionPathType pathtype;
762
0
  Oid     funcId;
763
764
  /* Skip coercion if already done */
765
0
  if (targetTypMod == exprTypmod(node))
766
0
    return node;
767
768
  /* Suppress display of nested coercion steps */
769
0
  if (hideInputCoercion)
770
0
    hide_coercion_node(node);
771
772
  /*
773
   * A negative typmod means that no actual coercion is needed, but we still
774
   * want a RelabelType to ensure that the expression exposes the intended
775
   * typmod.
776
   */
777
0
  if (targetTypMod < 0)
778
0
    pathtype = COERCION_PATH_NONE;
779
0
  else
780
0
    pathtype = find_typmod_coercion_function(targetTypeId, &funcId);
781
782
0
  if (pathtype != COERCION_PATH_NONE)
783
0
  {
784
0
    node = build_coercion_expression(node, pathtype, funcId,
785
0
                     targetTypeId, targetTypMod,
786
0
                     ccontext, cformat, location);
787
0
  }
788
0
  else
789
0
  {
790
    /*
791
     * We don't need to perform any actual coercion step, but we should
792
     * apply a RelabelType to ensure that the expression exposes the
793
     * intended typmod.
794
     */
795
0
    node = applyRelabelType(node, targetTypeId, targetTypMod,
796
0
                exprCollation(node),
797
0
                cformat, location, false);
798
0
  }
799
800
0
  return node;
801
0
}
802
803
/*
804
 * Mark a coercion node as IMPLICIT so it will never be displayed by
805
 * ruleutils.c.  We use this when we generate a nest of coercion nodes
806
 * to implement what is logically one conversion; the inner nodes are
807
 * forced to IMPLICIT_CAST format.  This does not change their semantics,
808
 * only display behavior.
809
 *
810
 * It is caller error to call this on something that doesn't have a
811
 * CoercionForm field.
812
 */
813
static void
814
hide_coercion_node(Node *node)
815
0
{
816
0
  if (IsA(node, FuncExpr))
817
0
    ((FuncExpr *) node)->funcformat = COERCE_IMPLICIT_CAST;
818
0
  else if (IsA(node, RelabelType))
819
0
    ((RelabelType *) node)->relabelformat = COERCE_IMPLICIT_CAST;
820
0
  else if (IsA(node, CoerceViaIO))
821
0
    ((CoerceViaIO *) node)->coerceformat = COERCE_IMPLICIT_CAST;
822
0
  else if (IsA(node, ArrayCoerceExpr))
823
0
    ((ArrayCoerceExpr *) node)->coerceformat = COERCE_IMPLICIT_CAST;
824
0
  else if (IsA(node, ConvertRowtypeExpr))
825
0
    ((ConvertRowtypeExpr *) node)->convertformat = COERCE_IMPLICIT_CAST;
826
0
  else if (IsA(node, RowExpr))
827
0
    ((RowExpr *) node)->row_format = COERCE_IMPLICIT_CAST;
828
0
  else if (IsA(node, CoerceToDomain))
829
0
    ((CoerceToDomain *) node)->coercionformat = COERCE_IMPLICIT_CAST;
830
0
  else
831
0
    elog(ERROR, "unsupported node type: %d", (int) nodeTag(node));
832
0
}
833
834
/*
835
 * build_coercion_expression()
836
 *    Construct an expression tree for applying a pg_cast entry.
837
 *
838
 * This is used for both type-coercion and length-coercion operations,
839
 * since there is no difference in terms of the calling convention.
840
 */
841
static Node *
842
build_coercion_expression(Node *node,
843
              CoercionPathType pathtype,
844
              Oid funcId,
845
              Oid targetTypeId, int32 targetTypMod,
846
              CoercionContext ccontext, CoercionForm cformat,
847
              int location)
848
0
{
849
0
  int     nargs = 0;
850
851
0
  if (OidIsValid(funcId))
852
0
  {
853
0
    HeapTuple tp;
854
0
    Form_pg_proc procstruct;
855
856
0
    tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcId));
857
0
    if (!HeapTupleIsValid(tp))
858
0
      elog(ERROR, "cache lookup failed for function %u", funcId);
859
0
    procstruct = (Form_pg_proc) GETSTRUCT(tp);
860
861
    /*
862
     * These Asserts essentially check that function is a legal coercion
863
     * function.  We can't make the seemingly obvious tests on prorettype
864
     * and proargtypes[0], even in the COERCION_PATH_FUNC case, because of
865
     * various binary-compatibility cases.
866
     */
867
    /* Assert(targetTypeId == procstruct->prorettype); */
868
0
    Assert(!procstruct->proretset);
869
0
    Assert(procstruct->prokind == PROKIND_FUNCTION);
870
0
    nargs = procstruct->pronargs;
871
0
    Assert(nargs >= 1 && nargs <= 3);
872
    /* Assert(procstruct->proargtypes.values[0] == exprType(node)); */
873
0
    Assert(nargs < 2 || procstruct->proargtypes.values[1] == INT4OID);
874
0
    Assert(nargs < 3 || procstruct->proargtypes.values[2] == BOOLOID);
875
876
0
    ReleaseSysCache(tp);
877
0
  }
878
879
0
  if (pathtype == COERCION_PATH_FUNC)
880
0
  {
881
    /* We build an ordinary FuncExpr with special arguments */
882
0
    FuncExpr   *fexpr;
883
0
    List     *args;
884
0
    Const    *cons;
885
886
0
    Assert(OidIsValid(funcId));
887
888
0
    args = list_make1(node);
889
890
0
    if (nargs >= 2)
891
0
    {
892
      /* Pass target typmod as an int4 constant */
893
0
      cons = makeConst(INT4OID,
894
0
               -1,
895
0
               InvalidOid,
896
0
               sizeof(int32),
897
0
               Int32GetDatum(targetTypMod),
898
0
               false,
899
0
               true);
900
901
0
      args = lappend(args, cons);
902
0
    }
903
904
0
    if (nargs == 3)
905
0
    {
906
      /* Pass it a boolean isExplicit parameter, too */
907
0
      cons = makeConst(BOOLOID,
908
0
               -1,
909
0
               InvalidOid,
910
0
               sizeof(bool),
911
0
               BoolGetDatum(ccontext == COERCION_EXPLICIT),
912
0
               false,
913
0
               true);
914
915
0
      args = lappend(args, cons);
916
0
    }
917
918
0
    fexpr = makeFuncExpr(funcId, targetTypeId, args,
919
0
               InvalidOid, InvalidOid, cformat);
920
0
    fexpr->location = location;
921
0
    return (Node *) fexpr;
922
0
  }
923
0
  else if (pathtype == COERCION_PATH_ARRAYCOERCE)
924
0
  {
925
    /* We need to build an ArrayCoerceExpr */
926
0
    ArrayCoerceExpr *acoerce = makeNode(ArrayCoerceExpr);
927
0
    CaseTestExpr *ctest = makeNode(CaseTestExpr);
928
0
    Oid     sourceBaseTypeId;
929
0
    int32   sourceBaseTypeMod;
930
0
    Oid     targetElementType;
931
0
    Node     *elemexpr;
932
933
    /*
934
     * Look through any domain over the source array type.  Note we don't
935
     * expect that the target type is a domain; it must be a plain array.
936
     * (To get to a domain target type, we'll do coerce_to_domain later.)
937
     */
938
0
    sourceBaseTypeMod = exprTypmod(node);
939
0
    sourceBaseTypeId = getBaseTypeAndTypmod(exprType(node),
940
0
                        &sourceBaseTypeMod);
941
942
    /*
943
     * Set up a CaseTestExpr representing one element of the source array.
944
     * This is an abuse of CaseTestExpr, but it's OK as long as there
945
     * can't be any CaseExpr or ArrayCoerceExpr within the completed
946
     * elemexpr.
947
     */
948
0
    ctest->typeId = get_element_type(sourceBaseTypeId);
949
0
    Assert(OidIsValid(ctest->typeId));
950
0
    ctest->typeMod = sourceBaseTypeMod;
951
0
    ctest->collation = InvalidOid; /* Assume coercions don't care */
952
953
    /* And coerce it to the target element type */
954
0
    targetElementType = get_element_type(targetTypeId);
955
0
    Assert(OidIsValid(targetElementType));
956
957
0
    elemexpr = coerce_to_target_type(NULL,
958
0
                     (Node *) ctest,
959
0
                     ctest->typeId,
960
0
                     targetElementType,
961
0
                     targetTypMod,
962
0
                     ccontext,
963
0
                     cformat,
964
0
                     location);
965
0
    if (elemexpr == NULL) /* shouldn't happen */
966
0
      elog(ERROR, "failed to coerce array element type as expected");
967
968
0
    acoerce->arg = (Expr *) node;
969
0
    acoerce->elemexpr = (Expr *) elemexpr;
970
0
    acoerce->resulttype = targetTypeId;
971
972
    /*
973
     * Label the output as having a particular element typmod only if we
974
     * ended up with a per-element expression that is labeled that way.
975
     */
976
0
    acoerce->resulttypmod = exprTypmod(elemexpr);
977
    /* resultcollid will be set by parse_collate.c */
978
0
    acoerce->coerceformat = cformat;
979
0
    acoerce->location = location;
980
981
0
    return (Node *) acoerce;
982
0
  }
983
0
  else if (pathtype == COERCION_PATH_COERCEVIAIO)
984
0
  {
985
    /* We need to build a CoerceViaIO node */
986
0
    CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
987
988
0
    Assert(!OidIsValid(funcId));
989
990
0
    iocoerce->arg = (Expr *) node;
991
0
    iocoerce->resulttype = targetTypeId;
992
    /* resultcollid will be set by parse_collate.c */
993
0
    iocoerce->coerceformat = cformat;
994
0
    iocoerce->location = location;
995
996
0
    return (Node *) iocoerce;
997
0
  }
998
0
  else
999
0
  {
1000
0
    elog(ERROR, "unsupported pathtype %d in build_coercion_expression",
1001
0
       (int) pathtype);
1002
0
    return NULL;     /* keep compiler quiet */
1003
0
  }
1004
0
}
1005
1006
1007
/*
1008
 * coerce_record_to_complex
1009
 *    Coerce a RECORD to a specific composite type.
1010
 *
1011
 * Currently we only support this for inputs that are RowExprs or whole-row
1012
 * Vars.
1013
 */
1014
static Node *
1015
coerce_record_to_complex(ParseState *pstate, Node *node,
1016
             Oid targetTypeId,
1017
             CoercionContext ccontext,
1018
             CoercionForm cformat,
1019
             int location)
1020
0
{
1021
0
  RowExpr    *rowexpr;
1022
0
  Oid     baseTypeId;
1023
0
  int32   baseTypeMod = -1;
1024
0
  TupleDesc tupdesc;
1025
0
  List     *args = NIL;
1026
0
  List     *newargs;
1027
0
  int     i;
1028
0
  int     ucolno;
1029
0
  ListCell   *arg;
1030
1031
0
  if (node && IsA(node, RowExpr))
1032
0
  {
1033
    /*
1034
     * Since the RowExpr must be of type RECORD, we needn't worry about it
1035
     * containing any dropped columns.
1036
     */
1037
0
    args = ((RowExpr *) node)->args;
1038
0
  }
1039
0
  else if (node && IsA(node, Var) &&
1040
0
       ((Var *) node)->varattno == InvalidAttrNumber)
1041
0
  {
1042
0
    Var      *var = (Var *) node;
1043
0
    ParseNamespaceItem *nsitem;
1044
1045
0
    nsitem = GetNSItemByVar(pstate, var);
1046
0
    args = expandNSItemVars(pstate, nsitem, var->varlevelsup,
1047
0
                var->location, NULL);
1048
0
  }
1049
0
  else
1050
0
    ereport(ERROR,
1051
0
        (errcode(ERRCODE_CANNOT_COERCE),
1052
0
         errmsg("cannot cast type %s to %s",
1053
0
            format_type_be(RECORDOID),
1054
0
            format_type_be(targetTypeId)),
1055
0
         parser_coercion_errposition(pstate, location, node)));
1056
1057
  /*
1058
   * Look up the composite type, accounting for possibility that what we are
1059
   * given is a domain over composite.
1060
   */
1061
0
  baseTypeId = getBaseTypeAndTypmod(targetTypeId, &baseTypeMod);
1062
0
  tupdesc = lookup_rowtype_tupdesc(baseTypeId, baseTypeMod);
1063
1064
  /* Process the fields */
1065
0
  newargs = NIL;
1066
0
  ucolno = 1;
1067
0
  arg = list_head(args);
1068
0
  for (i = 0; i < tupdesc->natts; i++)
1069
0
  {
1070
0
    Node     *expr;
1071
0
    Node     *cexpr;
1072
0
    Oid     exprtype;
1073
0
    Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
1074
1075
    /* Fill in NULLs for dropped columns in rowtype */
1076
0
    if (attr->attisdropped)
1077
0
    {
1078
      /*
1079
       * can't use atttypid here, but it doesn't really matter what type
1080
       * the Const claims to be.
1081
       */
1082
0
      newargs = lappend(newargs,
1083
0
                makeNullConst(INT4OID, -1, InvalidOid));
1084
0
      continue;
1085
0
    }
1086
1087
0
    if (arg == NULL)
1088
0
      ereport(ERROR,
1089
0
          (errcode(ERRCODE_CANNOT_COERCE),
1090
0
           errmsg("cannot cast type %s to %s",
1091
0
              format_type_be(RECORDOID),
1092
0
              format_type_be(targetTypeId)),
1093
0
           errdetail("Input has too few columns."),
1094
0
           parser_coercion_errposition(pstate, location, node)));
1095
0
    expr = (Node *) lfirst(arg);
1096
0
    exprtype = exprType(expr);
1097
1098
0
    cexpr = coerce_to_target_type(pstate,
1099
0
                    expr, exprtype,
1100
0
                    attr->atttypid,
1101
0
                    attr->atttypmod,
1102
0
                    ccontext,
1103
0
                    COERCE_IMPLICIT_CAST,
1104
0
                    -1);
1105
0
    if (cexpr == NULL)
1106
0
      ereport(ERROR,
1107
0
          (errcode(ERRCODE_CANNOT_COERCE),
1108
0
           errmsg("cannot cast type %s to %s",
1109
0
              format_type_be(RECORDOID),
1110
0
              format_type_be(targetTypeId)),
1111
0
           errdetail("Cannot cast type %s to %s in column %d.",
1112
0
                 format_type_be(exprtype),
1113
0
                 format_type_be(attr->atttypid),
1114
0
                 ucolno),
1115
0
           parser_coercion_errposition(pstate, location, expr)));
1116
0
    newargs = lappend(newargs, cexpr);
1117
0
    ucolno++;
1118
0
    arg = lnext(args, arg);
1119
0
  }
1120
0
  if (arg != NULL)
1121
0
    ereport(ERROR,
1122
0
        (errcode(ERRCODE_CANNOT_COERCE),
1123
0
         errmsg("cannot cast type %s to %s",
1124
0
            format_type_be(RECORDOID),
1125
0
            format_type_be(targetTypeId)),
1126
0
         errdetail("Input has too many columns."),
1127
0
         parser_coercion_errposition(pstate, location, node)));
1128
1129
0
  ReleaseTupleDesc(tupdesc);
1130
1131
0
  rowexpr = makeNode(RowExpr);
1132
0
  rowexpr->args = newargs;
1133
0
  rowexpr->row_typeid = baseTypeId;
1134
0
  rowexpr->row_format = cformat;
1135
0
  rowexpr->colnames = NIL; /* not needed for named target type */
1136
0
  rowexpr->location = location;
1137
1138
  /* If target is a domain, apply constraints */
1139
0
  if (baseTypeId != targetTypeId)
1140
0
  {
1141
0
    rowexpr->row_format = COERCE_IMPLICIT_CAST;
1142
0
    return coerce_to_domain((Node *) rowexpr,
1143
0
                baseTypeId, baseTypeMod,
1144
0
                targetTypeId,
1145
0
                ccontext, cformat, location,
1146
0
                false);
1147
0
  }
1148
1149
0
  return (Node *) rowexpr;
1150
0
}
1151
1152
/*
1153
 * coerce_to_boolean()
1154
 *    Coerce an argument of a construct that requires boolean input
1155
 *    (AND, OR, NOT, etc).  Also check that input is not a set.
1156
 *
1157
 * Returns the possibly-transformed node tree.
1158
 *
1159
 * As with coerce_type, pstate may be NULL if no special unknown-Param
1160
 * processing is wanted.
1161
 */
1162
Node *
1163
coerce_to_boolean(ParseState *pstate, Node *node,
1164
          const char *constructName)
1165
0
{
1166
0
  Oid     inputTypeId = exprType(node);
1167
1168
0
  if (inputTypeId != BOOLOID)
1169
0
  {
1170
0
    Node     *newnode;
1171
1172
0
    newnode = coerce_to_target_type(pstate, node, inputTypeId,
1173
0
                    BOOLOID, -1,
1174
0
                    COERCION_ASSIGNMENT,
1175
0
                    COERCE_IMPLICIT_CAST,
1176
0
                    -1);
1177
0
    if (newnode == NULL)
1178
0
      ereport(ERROR,
1179
0
          (errcode(ERRCODE_DATATYPE_MISMATCH),
1180
      /* translator: first %s is name of a SQL construct, eg WHERE */
1181
0
           errmsg("argument of %s must be type %s, not type %s",
1182
0
              constructName, "boolean",
1183
0
              format_type_be(inputTypeId)),
1184
0
           parser_errposition(pstate, exprLocation(node))));
1185
0
    node = newnode;
1186
0
  }
1187
1188
0
  if (expression_returns_set(node))
1189
0
    ereport(ERROR,
1190
0
        (errcode(ERRCODE_DATATYPE_MISMATCH),
1191
    /* translator: %s is name of a SQL construct, eg WHERE */
1192
0
         errmsg("argument of %s must not return a set",
1193
0
            constructName),
1194
0
         parser_errposition(pstate, exprLocation(node))));
1195
1196
0
  return node;
1197
0
}
1198
1199
/*
1200
 * coerce_to_specific_type_typmod()
1201
 *    Coerce an argument of a construct that requires a specific data type,
1202
 *    with a specific typmod.  Also check that input is not a set.
1203
 *
1204
 * Returns the possibly-transformed node tree.
1205
 *
1206
 * As with coerce_type, pstate may be NULL if no special unknown-Param
1207
 * processing is wanted.
1208
 */
1209
Node *
1210
coerce_to_specific_type_typmod(ParseState *pstate, Node *node,
1211
                 Oid targetTypeId, int32 targetTypmod,
1212
                 const char *constructName)
1213
0
{
1214
0
  Oid     inputTypeId = exprType(node);
1215
1216
0
  if (inputTypeId != targetTypeId)
1217
0
  {
1218
0
    Node     *newnode;
1219
1220
0
    newnode = coerce_to_target_type(pstate, node, inputTypeId,
1221
0
                    targetTypeId, targetTypmod,
1222
0
                    COERCION_ASSIGNMENT,
1223
0
                    COERCE_IMPLICIT_CAST,
1224
0
                    -1);
1225
0
    if (newnode == NULL)
1226
0
      ereport(ERROR,
1227
0
          (errcode(ERRCODE_DATATYPE_MISMATCH),
1228
      /* translator: first %s is name of a SQL construct, eg LIMIT */
1229
0
           errmsg("argument of %s must be type %s, not type %s",
1230
0
              constructName,
1231
0
              format_type_be(targetTypeId),
1232
0
              format_type_be(inputTypeId)),
1233
0
           parser_errposition(pstate, exprLocation(node))));
1234
0
    node = newnode;
1235
0
  }
1236
1237
0
  if (expression_returns_set(node))
1238
0
    ereport(ERROR,
1239
0
        (errcode(ERRCODE_DATATYPE_MISMATCH),
1240
    /* translator: %s is name of a SQL construct, eg LIMIT */
1241
0
         errmsg("argument of %s must not return a set",
1242
0
            constructName),
1243
0
         parser_errposition(pstate, exprLocation(node))));
1244
1245
0
  return node;
1246
0
}
1247
1248
/*
1249
 * coerce_to_specific_type()
1250
 *    Coerce an argument of a construct that requires a specific data type.
1251
 *    Also check that input is not a set.
1252
 *
1253
 * Returns the possibly-transformed node tree.
1254
 *
1255
 * As with coerce_type, pstate may be NULL if no special unknown-Param
1256
 * processing is wanted.
1257
 */
1258
Node *
1259
coerce_to_specific_type(ParseState *pstate, Node *node,
1260
            Oid targetTypeId,
1261
            const char *constructName)
1262
0
{
1263
0
  return coerce_to_specific_type_typmod(pstate, node,
1264
0
                      targetTypeId, -1,
1265
0
                      constructName);
1266
0
}
1267
1268
/*
1269
 * coerce_null_to_domain()
1270
 *    Build a NULL constant, then wrap it in CoerceToDomain
1271
 *    if the desired type is a domain type.  This allows any
1272
 *    NOT NULL domain constraint to be enforced at runtime.
1273
 */
1274
Node *
1275
coerce_null_to_domain(Oid typid, int32 typmod, Oid collation,
1276
            int typlen, bool typbyval)
1277
0
{
1278
0
  Node     *result;
1279
0
  Oid     baseTypeId;
1280
0
  int32   baseTypeMod = typmod;
1281
1282
  /*
1283
   * The constant must appear to have the domain's base type/typmod, else
1284
   * coerce_to_domain() will apply a length coercion which is useless.
1285
   */
1286
0
  baseTypeId = getBaseTypeAndTypmod(typid, &baseTypeMod);
1287
0
  result = (Node *) makeConst(baseTypeId,
1288
0
                baseTypeMod,
1289
0
                collation,
1290
0
                typlen,
1291
0
                (Datum) 0,
1292
0
                true, /* isnull */
1293
0
                typbyval);
1294
0
  if (typid != baseTypeId)
1295
0
    result = coerce_to_domain(result,
1296
0
                  baseTypeId, baseTypeMod,
1297
0
                  typid,
1298
0
                  COERCION_IMPLICIT,
1299
0
                  COERCE_IMPLICIT_CAST,
1300
0
                  -1,
1301
0
                  false);
1302
0
  return result;
1303
0
}
1304
1305
/*
1306
 * parser_coercion_errposition - report coercion error location, if possible
1307
 *
1308
 * We prefer to point at the coercion request (CAST, ::, etc) if possible;
1309
 * but there may be no such location in the case of an implicit coercion.
1310
 * In that case point at the input expression.
1311
 *
1312
 * XXX possibly this is more generally useful than coercion errors;
1313
 * if so, should rename and place with parser_errposition.
1314
 */
1315
int
1316
parser_coercion_errposition(ParseState *pstate,
1317
              int coerce_location,
1318
              Node *input_expr)
1319
0
{
1320
0
  if (coerce_location >= 0)
1321
0
    return parser_errposition(pstate, coerce_location);
1322
0
  else
1323
0
    return parser_errposition(pstate, exprLocation(input_expr));
1324
0
}
1325
1326
1327
/*
1328
 * select_common_type()
1329
 *    Determine the common supertype of a list of input expressions.
1330
 *    This is used for determining the output type of CASE, UNION,
1331
 *    and similar constructs.
1332
 *
1333
 * 'exprs' is a *nonempty* list of expressions.  Note that earlier items
1334
 * in the list will be preferred if there is doubt.
1335
 * 'context' is a phrase to use in the error message if we fail to select
1336
 * a usable type.  Pass NULL to have the routine return InvalidOid
1337
 * rather than throwing an error on failure.
1338
 * 'which_expr': if not NULL, receives a pointer to the particular input
1339
 * expression from which the result type was taken.
1340
 *
1341
 * Caution: "failure" just means that there were inputs of different type
1342
 * categories.  It is not guaranteed that all the inputs are coercible to the
1343
 * selected type; caller must check that (see verify_common_type).
1344
 */
1345
Oid
1346
select_common_type(ParseState *pstate, List *exprs, const char *context,
1347
           Node **which_expr)
1348
0
{
1349
0
  Node     *pexpr;
1350
0
  Oid     ptype;
1351
0
  TYPCATEGORY pcategory;
1352
0
  bool    pispreferred;
1353
0
  ListCell   *lc;
1354
1355
0
  Assert(exprs != NIL);
1356
0
  pexpr = (Node *) linitial(exprs);
1357
0
  lc = list_second_cell(exprs);
1358
0
  ptype = exprType(pexpr);
1359
1360
  /*
1361
   * If all input types are valid and exactly the same, just pick that type.
1362
   * This is the only way that we will resolve the result as being a domain
1363
   * type; otherwise domains are smashed to their base types for comparison.
1364
   */
1365
0
  if (ptype != UNKNOWNOID)
1366
0
  {
1367
0
    for_each_cell(lc, exprs, lc)
1368
0
    {
1369
0
      Node     *nexpr = (Node *) lfirst(lc);
1370
0
      Oid     ntype = exprType(nexpr);
1371
1372
0
      if (ntype != ptype)
1373
0
        break;
1374
0
    }
1375
0
    if (lc == NULL)     /* got to the end of the list? */
1376
0
    {
1377
0
      if (which_expr)
1378
0
        *which_expr = pexpr;
1379
0
      return ptype;
1380
0
    }
1381
0
  }
1382
1383
  /*
1384
   * Nope, so set up for the full algorithm.  Note that at this point, lc
1385
   * points to the first list item with type different from pexpr's; we need
1386
   * not re-examine any items the previous loop advanced over.
1387
   */
1388
0
  ptype = getBaseType(ptype);
1389
0
  get_type_category_preferred(ptype, &pcategory, &pispreferred);
1390
1391
0
  for_each_cell(lc, exprs, lc)
1392
0
  {
1393
0
    Node     *nexpr = (Node *) lfirst(lc);
1394
0
    Oid     ntype = getBaseType(exprType(nexpr));
1395
1396
    /* move on to next one if no new information... */
1397
0
    if (ntype != UNKNOWNOID && ntype != ptype)
1398
0
    {
1399
0
      TYPCATEGORY ncategory;
1400
0
      bool    nispreferred;
1401
1402
0
      get_type_category_preferred(ntype, &ncategory, &nispreferred);
1403
0
      if (ptype == UNKNOWNOID)
1404
0
      {
1405
        /* so far, only unknowns so take anything... */
1406
0
        pexpr = nexpr;
1407
0
        ptype = ntype;
1408
0
        pcategory = ncategory;
1409
0
        pispreferred = nispreferred;
1410
0
      }
1411
0
      else if (ncategory != pcategory)
1412
0
      {
1413
        /*
1414
         * both types in different categories? then not much hope...
1415
         */
1416
0
        if (context == NULL)
1417
0
          return InvalidOid;
1418
0
        ereport(ERROR,
1419
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
1420
        /*------
1421
          translator: first %s is name of a SQL construct, eg CASE */
1422
0
             errmsg("%s types %s and %s cannot be matched",
1423
0
                context,
1424
0
                format_type_be(ptype),
1425
0
                format_type_be(ntype)),
1426
0
             parser_errposition(pstate, exprLocation(nexpr))));
1427
0
      }
1428
0
      else if (!pispreferred &&
1429
0
           can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1430
0
           !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1431
0
      {
1432
        /*
1433
         * take new type if can coerce to it implicitly but not the
1434
         * other way; but if we have a preferred type, stay on it.
1435
         */
1436
0
        pexpr = nexpr;
1437
0
        ptype = ntype;
1438
0
        pcategory = ncategory;
1439
0
        pispreferred = nispreferred;
1440
0
      }
1441
0
    }
1442
0
  }
1443
1444
  /*
1445
   * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
1446
   * then resolve as type TEXT.  This situation comes up with constructs
1447
   * like SELECT (CASE WHEN foo THEN 'bar' ELSE 'baz' END); SELECT 'foo'
1448
   * UNION SELECT 'bar'; It might seem desirable to leave the construct's
1449
   * output type as UNKNOWN, but that really doesn't work, because we'd
1450
   * probably end up needing a runtime coercion from UNKNOWN to something
1451
   * else, and we usually won't have it.  We need to coerce the unknown
1452
   * literals while they are still literals, so a decision has to be made
1453
   * now.
1454
   */
1455
0
  if (ptype == UNKNOWNOID)
1456
0
    ptype = TEXTOID;
1457
1458
0
  if (which_expr)
1459
0
    *which_expr = pexpr;
1460
0
  return ptype;
1461
0
}
1462
1463
/*
1464
 * select_common_type_from_oids()
1465
 *    Determine the common supertype of an array of type OIDs.
1466
 *
1467
 * This is the same logic as select_common_type(), but working from
1468
 * an array of type OIDs not a list of expressions.  As in that function,
1469
 * earlier entries in the array have some preference over later ones.
1470
 * On failure, return InvalidOid if noerror is true, else throw an error.
1471
 *
1472
 * Caution: "failure" just means that there were inputs of different type
1473
 * categories.  It is not guaranteed that all the inputs are coercible to the
1474
 * selected type; caller must check that (see verify_common_type_from_oids).
1475
 *
1476
 * Note: neither caller will pass any UNKNOWNOID entries, so the tests
1477
 * for that in this function are dead code.  However, they don't cost much,
1478
 * and it seems better to keep this logic as close to select_common_type()
1479
 * as possible.
1480
 */
1481
static Oid
1482
select_common_type_from_oids(int nargs, const Oid *typeids, bool noerror)
1483
0
{
1484
0
  Oid     ptype;
1485
0
  TYPCATEGORY pcategory;
1486
0
  bool    pispreferred;
1487
0
  int     i = 1;
1488
1489
0
  Assert(nargs > 0);
1490
0
  ptype = typeids[0];
1491
1492
  /* If all input types are valid and exactly the same, pick that type. */
1493
0
  if (ptype != UNKNOWNOID)
1494
0
  {
1495
0
    for (; i < nargs; i++)
1496
0
    {
1497
0
      if (typeids[i] != ptype)
1498
0
        break;
1499
0
    }
1500
0
    if (i == nargs)
1501
0
      return ptype;
1502
0
  }
1503
1504
  /*
1505
   * Nope, so set up for the full algorithm.  Note that at this point, we
1506
   * can skip array entries before "i"; they are all equal to ptype.
1507
   */
1508
0
  ptype = getBaseType(ptype);
1509
0
  get_type_category_preferred(ptype, &pcategory, &pispreferred);
1510
1511
0
  for (; i < nargs; i++)
1512
0
  {
1513
0
    Oid     ntype = getBaseType(typeids[i]);
1514
1515
    /* move on to next one if no new information... */
1516
0
    if (ntype != UNKNOWNOID && ntype != ptype)
1517
0
    {
1518
0
      TYPCATEGORY ncategory;
1519
0
      bool    nispreferred;
1520
1521
0
      get_type_category_preferred(ntype, &ncategory, &nispreferred);
1522
0
      if (ptype == UNKNOWNOID)
1523
0
      {
1524
        /* so far, only unknowns so take anything... */
1525
0
        ptype = ntype;
1526
0
        pcategory = ncategory;
1527
0
        pispreferred = nispreferred;
1528
0
      }
1529
0
      else if (ncategory != pcategory)
1530
0
      {
1531
        /*
1532
         * both types in different categories? then not much hope...
1533
         */
1534
0
        if (noerror)
1535
0
          return InvalidOid;
1536
0
        ereport(ERROR,
1537
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
1538
0
             errmsg("argument types %s and %s cannot be matched",
1539
0
                format_type_be(ptype),
1540
0
                format_type_be(ntype))));
1541
0
      }
1542
0
      else if (!pispreferred &&
1543
0
           can_coerce_type(1, &ptype, &ntype, COERCION_IMPLICIT) &&
1544
0
           !can_coerce_type(1, &ntype, &ptype, COERCION_IMPLICIT))
1545
0
      {
1546
        /*
1547
         * take new type if can coerce to it implicitly but not the
1548
         * other way; but if we have a preferred type, stay on it.
1549
         */
1550
0
        ptype = ntype;
1551
0
        pcategory = ncategory;
1552
0
        pispreferred = nispreferred;
1553
0
      }
1554
0
    }
1555
0
  }
1556
1557
  /* Like select_common_type(), choose TEXT if all inputs were UNKNOWN */
1558
0
  if (ptype == UNKNOWNOID)
1559
0
    ptype = TEXTOID;
1560
1561
0
  return ptype;
1562
0
}
1563
1564
/*
1565
 * coerce_to_common_type()
1566
 *    Coerce an expression to the given type.
1567
 *
1568
 * This is used following select_common_type() to coerce the individual
1569
 * expressions to the desired type.  'context' is a phrase to use in the
1570
 * error message if we fail to coerce.
1571
 *
1572
 * As with coerce_type, pstate may be NULL if no special unknown-Param
1573
 * processing is wanted.
1574
 */
1575
Node *
1576
coerce_to_common_type(ParseState *pstate, Node *node,
1577
            Oid targetTypeId, const char *context)
1578
0
{
1579
0
  Oid     inputTypeId = exprType(node);
1580
1581
0
  if (inputTypeId == targetTypeId)
1582
0
    return node;     /* no work */
1583
0
  if (can_coerce_type(1, &inputTypeId, &targetTypeId, COERCION_IMPLICIT))
1584
0
    node = coerce_type(pstate, node, inputTypeId, targetTypeId, -1,
1585
0
               COERCION_IMPLICIT, COERCE_IMPLICIT_CAST, -1);
1586
0
  else
1587
0
    ereport(ERROR,
1588
0
        (errcode(ERRCODE_CANNOT_COERCE),
1589
    /* translator: first %s is name of a SQL construct, eg CASE */
1590
0
         errmsg("%s could not convert type %s to %s",
1591
0
            context,
1592
0
            format_type_be(inputTypeId),
1593
0
            format_type_be(targetTypeId)),
1594
0
         parser_errposition(pstate, exprLocation(node))));
1595
0
  return node;
1596
0
}
1597
1598
/*
1599
 * verify_common_type()
1600
 *    Verify that all input types can be coerced to a proposed common type.
1601
 *    Return true if so, false if not all coercions are possible.
1602
 *
1603
 * Most callers of select_common_type() don't need to do this explicitly
1604
 * because the checks will happen while trying to convert input expressions
1605
 * to the right type, e.g. in coerce_to_common_type().  However, if a separate
1606
 * check step is needed to validate the applicability of the common type, call
1607
 * this.
1608
 */
1609
bool
1610
verify_common_type(Oid common_type, List *exprs)
1611
0
{
1612
0
  ListCell   *lc;
1613
1614
0
  foreach(lc, exprs)
1615
0
  {
1616
0
    Node     *nexpr = (Node *) lfirst(lc);
1617
0
    Oid     ntype = exprType(nexpr);
1618
1619
0
    if (!can_coerce_type(1, &ntype, &common_type, COERCION_IMPLICIT))
1620
0
      return false;
1621
0
  }
1622
0
  return true;
1623
0
}
1624
1625
/*
1626
 * verify_common_type_from_oids()
1627
 *    As above, but work from an array of type OIDs.
1628
 */
1629
static bool
1630
verify_common_type_from_oids(Oid common_type, int nargs, const Oid *typeids)
1631
0
{
1632
0
  for (int i = 0; i < nargs; i++)
1633
0
  {
1634
0
    if (!can_coerce_type(1, &typeids[i], &common_type, COERCION_IMPLICIT))
1635
0
      return false;
1636
0
  }
1637
0
  return true;
1638
0
}
1639
1640
/*
1641
 * select_common_typmod()
1642
 *    Determine the common typmod of a list of input expressions.
1643
 *
1644
 * common_type is the selected common type of the expressions, typically
1645
 * computed using select_common_type().
1646
 */
1647
int32
1648
select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
1649
0
{
1650
0
  ListCell   *lc;
1651
0
  bool    first = true;
1652
0
  int32   result = -1;
1653
1654
0
  foreach(lc, exprs)
1655
0
  {
1656
0
    Node     *expr = (Node *) lfirst(lc);
1657
1658
    /* Types must match */
1659
0
    if (exprType(expr) != common_type)
1660
0
      return -1;
1661
0
    else if (first)
1662
0
    {
1663
0
      result = exprTypmod(expr);
1664
0
      first = false;
1665
0
    }
1666
0
    else
1667
0
    {
1668
      /* As soon as we see a non-matching typmod, fall back to -1 */
1669
0
      if (result != exprTypmod(expr))
1670
0
        return -1;
1671
0
    }
1672
0
  }
1673
1674
0
  return result;
1675
0
}
1676
1677
/*
1678
 * check_generic_type_consistency()
1679
 *    Are the actual arguments potentially compatible with a
1680
 *    polymorphic function?
1681
 *
1682
 * The argument consistency rules are:
1683
 *
1684
 * 1) All arguments declared ANYELEMENT must have the same datatype.
1685
 * 2) All arguments declared ANYARRAY must have the same datatype,
1686
 *    which must be a varlena array type.
1687
 * 3) All arguments declared ANYRANGE must be the same range type.
1688
 *    Similarly, all arguments declared ANYMULTIRANGE must be the same
1689
 *    multirange type; and if both of these appear, the ANYRANGE type
1690
 *    must be the element type of the ANYMULTIRANGE type.
1691
 * 4) If there are arguments of more than one of these polymorphic types,
1692
 *    the array element type and/or range subtype must be the same as each
1693
 *    other and the same as the ANYELEMENT type.
1694
 * 5) ANYENUM is treated the same as ANYELEMENT except that if it is used
1695
 *    (alone or in combination with plain ANYELEMENT), we add the extra
1696
 *    condition that the ANYELEMENT type must be an enum.
1697
 * 6) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
1698
 *    we add the extra condition that the ANYELEMENT type must not be an array.
1699
 *    (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
1700
 *    is an extra restriction if not.)
1701
 * 7) All arguments declared ANYCOMPATIBLE must be implicitly castable
1702
 *    to a common supertype (chosen as per select_common_type's rules).
1703
 *    ANYCOMPATIBLENONARRAY works like ANYCOMPATIBLE but also requires the
1704
 *    common supertype to not be an array.  If there are ANYCOMPATIBLEARRAY
1705
 *    or ANYCOMPATIBLERANGE or ANYCOMPATIBLEMULTIRANGE arguments, their element
1706
 *    types or subtypes are included while making the choice of common supertype.
1707
 * 8) The resolved type of ANYCOMPATIBLEARRAY arguments will be the array
1708
 *    type over the common supertype (which might not be the same array type
1709
 *    as any of the original arrays).
1710
 * 9) All ANYCOMPATIBLERANGE arguments must be the exact same range type
1711
 *    (after domain flattening), since we have no preference rule that would
1712
 *    let us choose one over another.  Furthermore, that range's subtype
1713
 *    must exactly match the common supertype chosen by rule 7.
1714
 * 10) All ANYCOMPATIBLEMULTIRANGE arguments must be the exact same multirange
1715
 *    type (after domain flattening), since we have no preference rule that
1716
 *    would let us choose one over another.  Furthermore, if ANYCOMPATIBLERANGE
1717
 *    also appears, that range type must be the multirange's element type;
1718
 *    otherwise, the multirange's range's subtype must exactly match the
1719
 *    common supertype chosen by rule 7.
1720
 *
1721
 * Domains over arrays match ANYARRAY, and are immediately flattened to their
1722
 * base type.  (Thus, for example, we will consider it a match if one ANYARRAY
1723
 * argument is a domain over int4[] while another one is just int4[].)  Also
1724
 * notice that such a domain does *not* match ANYNONARRAY.  The same goes
1725
 * for ANYCOMPATIBLEARRAY and ANYCOMPATIBLENONARRAY.
1726
 *
1727
 * Similarly, domains over ranges match ANYRANGE or ANYCOMPATIBLERANGE,
1728
 * and are immediately flattened to their base type.  Likewise, domains
1729
 * over multiranges match ANYMULTIRANGE or ANYCOMPATIBLEMULTIRANGE and are
1730
 * immediately flattened to their base type.
1731
 *
1732
 * Note that domains aren't currently considered to match ANYENUM,
1733
 * even if their base type would match.
1734
 *
1735
 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
1736
 * argument, assume it is okay.
1737
 *
1738
 * We do not ereport here, but just return false if a rule is violated.
1739
 */
1740
bool
1741
check_generic_type_consistency(const Oid *actual_arg_types,
1742
                 const Oid *declared_arg_types,
1743
                 int nargs)
1744
0
{
1745
0
  Oid     elem_typeid = InvalidOid;
1746
0
  Oid     array_typeid = InvalidOid;
1747
0
  Oid     range_typeid = InvalidOid;
1748
0
  Oid     multirange_typeid = InvalidOid;
1749
0
  Oid     anycompatible_range_typeid = InvalidOid;
1750
0
  Oid     anycompatible_range_typelem = InvalidOid;
1751
0
  Oid     anycompatible_multirange_typeid = InvalidOid;
1752
0
  Oid     anycompatible_multirange_typelem = InvalidOid;
1753
0
  Oid     range_typelem = InvalidOid;
1754
0
  bool    have_anynonarray = false;
1755
0
  bool    have_anyenum = false;
1756
0
  bool    have_anycompatible_nonarray = false;
1757
0
  int     n_anycompatible_args = 0;
1758
0
  Oid     anycompatible_actual_types[FUNC_MAX_ARGS];
1759
1760
  /*
1761
   * Loop through the arguments to see if we have any that are polymorphic.
1762
   * If so, require the actual types to be consistent.
1763
   */
1764
0
  Assert(nargs <= FUNC_MAX_ARGS);
1765
0
  for (int j = 0; j < nargs; j++)
1766
0
  {
1767
0
    Oid     decl_type = declared_arg_types[j];
1768
0
    Oid     actual_type = actual_arg_types[j];
1769
1770
0
    if (decl_type == ANYELEMENTOID ||
1771
0
      decl_type == ANYNONARRAYOID ||
1772
0
      decl_type == ANYENUMOID)
1773
0
    {
1774
0
      if (decl_type == ANYNONARRAYOID)
1775
0
        have_anynonarray = true;
1776
0
      else if (decl_type == ANYENUMOID)
1777
0
        have_anyenum = true;
1778
0
      if (actual_type == UNKNOWNOID)
1779
0
        continue;
1780
0
      if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
1781
0
        return false;
1782
0
      elem_typeid = actual_type;
1783
0
    }
1784
0
    else if (decl_type == ANYARRAYOID)
1785
0
    {
1786
0
      if (actual_type == UNKNOWNOID)
1787
0
        continue;
1788
0
      actual_type = getBaseType(actual_type); /* flatten domains */
1789
0
      if (OidIsValid(array_typeid) && actual_type != array_typeid)
1790
0
        return false;
1791
0
      array_typeid = actual_type;
1792
0
    }
1793
0
    else if (decl_type == ANYRANGEOID)
1794
0
    {
1795
0
      if (actual_type == UNKNOWNOID)
1796
0
        continue;
1797
0
      actual_type = getBaseType(actual_type); /* flatten domains */
1798
0
      if (OidIsValid(range_typeid) && actual_type != range_typeid)
1799
0
        return false;
1800
0
      range_typeid = actual_type;
1801
0
    }
1802
0
    else if (decl_type == ANYMULTIRANGEOID)
1803
0
    {
1804
0
      if (actual_type == UNKNOWNOID)
1805
0
        continue;
1806
0
      actual_type = getBaseType(actual_type); /* flatten domains */
1807
0
      if (OidIsValid(multirange_typeid) && actual_type != multirange_typeid)
1808
0
        return false;
1809
0
      multirange_typeid = actual_type;
1810
0
    }
1811
0
    else if (decl_type == ANYCOMPATIBLEOID ||
1812
0
         decl_type == ANYCOMPATIBLENONARRAYOID)
1813
0
    {
1814
0
      if (decl_type == ANYCOMPATIBLENONARRAYOID)
1815
0
        have_anycompatible_nonarray = true;
1816
0
      if (actual_type == UNKNOWNOID)
1817
0
        continue;
1818
      /* collect the actual types of non-unknown COMPATIBLE args */
1819
0
      anycompatible_actual_types[n_anycompatible_args++] = actual_type;
1820
0
    }
1821
0
    else if (decl_type == ANYCOMPATIBLEARRAYOID)
1822
0
    {
1823
0
      Oid     elem_type;
1824
1825
0
      if (actual_type == UNKNOWNOID)
1826
0
        continue;
1827
0
      actual_type = getBaseType(actual_type); /* flatten domains */
1828
0
      elem_type = get_element_type(actual_type);
1829
0
      if (!OidIsValid(elem_type))
1830
0
        return false; /* not an array */
1831
      /* collect the element type for common-supertype choice */
1832
0
      anycompatible_actual_types[n_anycompatible_args++] = elem_type;
1833
0
    }
1834
0
    else if (decl_type == ANYCOMPATIBLERANGEOID)
1835
0
    {
1836
0
      if (actual_type == UNKNOWNOID)
1837
0
        continue;
1838
0
      actual_type = getBaseType(actual_type); /* flatten domains */
1839
0
      if (OidIsValid(anycompatible_range_typeid))
1840
0
      {
1841
        /* All ANYCOMPATIBLERANGE arguments must be the same type */
1842
0
        if (anycompatible_range_typeid != actual_type)
1843
0
          return false;
1844
0
      }
1845
0
      else
1846
0
      {
1847
0
        anycompatible_range_typeid = actual_type;
1848
0
        anycompatible_range_typelem = get_range_subtype(actual_type);
1849
0
        if (!OidIsValid(anycompatible_range_typelem))
1850
0
          return false; /* not a range type */
1851
        /* collect the subtype for common-supertype choice */
1852
0
        anycompatible_actual_types[n_anycompatible_args++] = anycompatible_range_typelem;
1853
0
      }
1854
0
    }
1855
0
    else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
1856
0
    {
1857
0
      if (actual_type == UNKNOWNOID)
1858
0
        continue;
1859
0
      actual_type = getBaseType(actual_type); /* flatten domains */
1860
0
      if (OidIsValid(anycompatible_multirange_typeid))
1861
0
      {
1862
        /* All ANYCOMPATIBLEMULTIRANGE arguments must be the same type */
1863
0
        if (anycompatible_multirange_typeid != actual_type)
1864
0
          return false;
1865
0
      }
1866
0
      else
1867
0
      {
1868
0
        anycompatible_multirange_typeid = actual_type;
1869
0
        anycompatible_multirange_typelem = get_multirange_range(actual_type);
1870
0
        if (!OidIsValid(anycompatible_multirange_typelem))
1871
0
          return false; /* not a multirange type */
1872
        /* we'll consider the subtype below */
1873
0
      }
1874
0
    }
1875
0
  }
1876
1877
  /* Get the element type based on the array type, if we have one */
1878
0
  if (OidIsValid(array_typeid))
1879
0
  {
1880
0
    if (array_typeid == ANYARRAYOID)
1881
0
    {
1882
      /*
1883
       * Special case for matching ANYARRAY input to an ANYARRAY
1884
       * argument: allow it for now.  enforce_generic_type_consistency()
1885
       * might complain later, depending on the presence of other
1886
       * polymorphic arguments or results, but it will deliver a less
1887
       * surprising error message than "function does not exist".
1888
       *
1889
       * (If you think to change this, note that can_coerce_type will
1890
       * consider such a situation as a match, so that we might not even
1891
       * get here.)
1892
       */
1893
0
    }
1894
0
    else
1895
0
    {
1896
0
      Oid     array_typelem;
1897
1898
0
      array_typelem = get_element_type(array_typeid);
1899
0
      if (!OidIsValid(array_typelem))
1900
0
        return false; /* should be an array, but isn't */
1901
1902
0
      if (!OidIsValid(elem_typeid))
1903
0
      {
1904
        /*
1905
         * if we don't have an element type yet, use the one we just
1906
         * got
1907
         */
1908
0
        elem_typeid = array_typelem;
1909
0
      }
1910
0
      else if (array_typelem != elem_typeid)
1911
0
      {
1912
        /* otherwise, they better match */
1913
0
        return false;
1914
0
      }
1915
0
    }
1916
0
  }
1917
1918
  /* Deduce range type from multirange type, or check that they agree */
1919
0
  if (OidIsValid(multirange_typeid))
1920
0
  {
1921
0
    Oid     multirange_typelem;
1922
1923
0
    multirange_typelem = get_multirange_range(multirange_typeid);
1924
0
    if (!OidIsValid(multirange_typelem))
1925
0
      return false;   /* should be a multirange, but isn't */
1926
1927
0
    if (!OidIsValid(range_typeid))
1928
0
    {
1929
      /* If we don't have a range type yet, use the one we just got */
1930
0
      range_typeid = multirange_typelem;
1931
0
      range_typelem = get_range_subtype(multirange_typelem);
1932
0
      if (!OidIsValid(range_typelem))
1933
0
        return false; /* should be a range, but isn't */
1934
0
    }
1935
0
    else if (multirange_typelem != range_typeid)
1936
0
    {
1937
      /* otherwise, they better match */
1938
0
      return false;
1939
0
    }
1940
0
  }
1941
1942
  /* Get the element type based on the range type, if we have one */
1943
0
  if (OidIsValid(range_typeid))
1944
0
  {
1945
0
    range_typelem = get_range_subtype(range_typeid);
1946
0
    if (!OidIsValid(range_typelem))
1947
0
      return false;   /* should be a range, but isn't */
1948
1949
0
    if (!OidIsValid(elem_typeid))
1950
0
    {
1951
      /*
1952
       * If we don't have an element type yet, use the one we just got
1953
       */
1954
0
      elem_typeid = range_typelem;
1955
0
    }
1956
0
    else if (range_typelem != elem_typeid)
1957
0
    {
1958
      /* otherwise, they better match */
1959
0
      return false;
1960
0
    }
1961
0
  }
1962
1963
0
  if (have_anynonarray)
1964
0
  {
1965
    /* require the element type to not be an array or domain over array */
1966
0
    if (type_is_array_domain(elem_typeid))
1967
0
      return false;
1968
0
  }
1969
1970
0
  if (have_anyenum)
1971
0
  {
1972
    /* require the element type to be an enum */
1973
0
    if (!type_is_enum(elem_typeid))
1974
0
      return false;
1975
0
  }
1976
1977
  /* Deduce range type from multirange type, or check that they agree */
1978
0
  if (OidIsValid(anycompatible_multirange_typeid))
1979
0
  {
1980
0
    if (OidIsValid(anycompatible_range_typeid))
1981
0
    {
1982
0
      if (anycompatible_multirange_typelem !=
1983
0
        anycompatible_range_typeid)
1984
0
        return false;
1985
0
    }
1986
0
    else
1987
0
    {
1988
0
      anycompatible_range_typeid = anycompatible_multirange_typelem;
1989
0
      anycompatible_range_typelem = get_range_subtype(anycompatible_range_typeid);
1990
0
      if (!OidIsValid(anycompatible_range_typelem))
1991
0
        return false; /* not a range type */
1992
      /* collect the subtype for common-supertype choice */
1993
0
      anycompatible_actual_types[n_anycompatible_args++] =
1994
0
        anycompatible_range_typelem;
1995
0
    }
1996
0
  }
1997
1998
  /* Check matching of ANYCOMPATIBLE-family arguments, if any */
1999
0
  if (n_anycompatible_args > 0)
2000
0
  {
2001
0
    Oid     anycompatible_typeid;
2002
2003
0
    anycompatible_typeid =
2004
0
      select_common_type_from_oids(n_anycompatible_args,
2005
0
                     anycompatible_actual_types,
2006
0
                     true);
2007
2008
0
    if (!OidIsValid(anycompatible_typeid))
2009
0
      return false;   /* there's definitely no common supertype */
2010
2011
    /* We have to verify that the selected type actually works */
2012
0
    if (!verify_common_type_from_oids(anycompatible_typeid,
2013
0
                      n_anycompatible_args,
2014
0
                      anycompatible_actual_types))
2015
0
      return false;
2016
2017
0
    if (have_anycompatible_nonarray)
2018
0
    {
2019
      /*
2020
       * require the anycompatible type to not be an array or domain
2021
       * over array
2022
       */
2023
0
      if (type_is_array_domain(anycompatible_typeid))
2024
0
        return false;
2025
0
    }
2026
2027
    /*
2028
     * The anycompatible type must exactly match the range element type,
2029
     * if we were able to identify one. This checks compatibility for
2030
     * anycompatiblemultirange too since that also sets
2031
     * anycompatible_range_typelem above.
2032
     */
2033
0
    if (OidIsValid(anycompatible_range_typelem) &&
2034
0
      anycompatible_range_typelem != anycompatible_typeid)
2035
0
      return false;
2036
0
  }
2037
2038
  /* Looks valid */
2039
0
  return true;
2040
0
}
2041
2042
/*
2043
 * enforce_generic_type_consistency()
2044
 *    Make sure a polymorphic function is legally callable, and
2045
 *    deduce actual argument and result types.
2046
 *
2047
 * If any polymorphic pseudotype is used in a function's arguments or
2048
 * return type, we make sure the actual data types are consistent with
2049
 * each other.  The argument consistency rules are shown above for
2050
 * check_generic_type_consistency().
2051
 *
2052
 * If we have UNKNOWN input (ie, an untyped literal) for any polymorphic
2053
 * argument, we attempt to deduce the actual type it should have.  If
2054
 * successful, we alter that position of declared_arg_types[] so that
2055
 * make_fn_arguments will coerce the literal to the right thing.
2056
 *
2057
 * If we have polymorphic arguments of the ANYCOMPATIBLE family,
2058
 * we similarly alter declared_arg_types[] entries to show the resolved
2059
 * common supertype, so that make_fn_arguments will coerce the actual
2060
 * arguments to the proper type.
2061
 *
2062
 * Rules are applied to the function's return type (possibly altering it)
2063
 * if it is declared as a polymorphic type and there is at least one
2064
 * polymorphic argument type:
2065
 *
2066
 * 1) If return type is ANYELEMENT, and any argument is ANYELEMENT, use the
2067
 *    argument's actual type as the function's return type.
2068
 * 2) If return type is ANYARRAY, and any argument is ANYARRAY, use the
2069
 *    argument's actual type as the function's return type.
2070
 * 3) Similarly, if return type is ANYRANGE or ANYMULTIRANGE, and any
2071
 *    argument is ANYRANGE or ANYMULTIRANGE, use that argument's actual type
2072
 *    (or the corresponding range or multirange type) as the function's return
2073
 *    type.
2074
 * 4) Otherwise, if return type is ANYELEMENT or ANYARRAY, and there is
2075
 *    at least one ANYELEMENT, ANYARRAY, ANYRANGE, or ANYMULTIRANGE input,
2076
 *    deduce the return type from those inputs, or throw error if we can't.
2077
 * 5) Otherwise, if return type is ANYRANGE or ANYMULTIRANGE, throw error.
2078
 *    (We have no way to select a specific range type if the arguments don't
2079
 *    include ANYRANGE or ANYMULTIRANGE.)
2080
 * 6) ANYENUM is treated the same as ANYELEMENT except that if it is used
2081
 *    (alone or in combination with plain ANYELEMENT), we add the extra
2082
 *    condition that the ANYELEMENT type must be an enum.
2083
 * 7) ANYNONARRAY is treated the same as ANYELEMENT except that if it is used,
2084
 *    we add the extra condition that the ANYELEMENT type must not be an array.
2085
 *    (This is a no-op if used in combination with ANYARRAY or ANYENUM, but
2086
 *    is an extra restriction if not.)
2087
 * 8) ANYCOMPATIBLE, ANYCOMPATIBLEARRAY, and ANYCOMPATIBLENONARRAY are handled
2088
 *    by resolving the common supertype of those arguments (or their element
2089
 *    types, for array inputs), and then coercing all those arguments to the
2090
 *    common supertype, or the array type over the common supertype for
2091
 *    ANYCOMPATIBLEARRAY.
2092
 * 9) For ANYCOMPATIBLERANGE and ANYCOMPATIBLEMULTIRANGE, there must be at
2093
 *    least one non-UNKNOWN input matching those arguments, and all such
2094
 *    inputs must be the same range type (or its multirange type, as
2095
 *    appropriate), since we cannot deduce a range type from non-range types.
2096
 *    Furthermore, the range type's subtype is included while choosing the
2097
 *    common supertype for ANYCOMPATIBLE et al, and it must exactly match
2098
 *    that common supertype.
2099
 *
2100
 * Domains over arrays or ranges match ANYARRAY or ANYRANGE arguments,
2101
 * respectively, and are immediately flattened to their base type.  (In
2102
 * particular, if the return type is also ANYARRAY or ANYRANGE, we'll set
2103
 * it to the base type not the domain type.)  The same is true for
2104
 * ANYMULTIRANGE, ANYCOMPATIBLEARRAY, ANYCOMPATIBLERANGE, and
2105
 * ANYCOMPATIBLEMULTIRANGE.
2106
 *
2107
 * When allow_poly is false, we are not expecting any of the actual_arg_types
2108
 * to be polymorphic, and we should not return a polymorphic result type
2109
 * either.  When allow_poly is true, it is okay to have polymorphic "actual"
2110
 * arg types, and we can return a matching polymorphic type as the result.
2111
 * (This case is currently used only to check compatibility of an aggregate's
2112
 * declaration with the underlying transfn.)
2113
 *
2114
 * A special case is that we could see ANYARRAY as an actual_arg_type even
2115
 * when allow_poly is false (this is possible only because pg_statistic has
2116
 * columns shown as anyarray in the catalogs).  We allow this to match a
2117
 * declared ANYARRAY argument, but only if there is no other polymorphic
2118
 * argument that we would need to match it with, and no need to determine
2119
 * the element type to infer the result type.  Note this means that functions
2120
 * taking ANYARRAY had better behave sanely if applied to the pg_statistic
2121
 * columns; they can't just assume that successive inputs are of the same
2122
 * actual element type.  There is no similar logic for ANYCOMPATIBLEARRAY;
2123
 * there isn't a need for it since there are no catalog columns of that type,
2124
 * so we won't see it as input.  We could consider matching an actual ANYARRAY
2125
 * input to an ANYCOMPATIBLEARRAY argument, but at present that seems useless
2126
 * as well, since there's no value in using ANYCOMPATIBLEARRAY unless there's
2127
 * at least one other ANYCOMPATIBLE-family argument or result.
2128
 *
2129
 * Also, if there are no arguments declared to be of polymorphic types,
2130
 * we'll return the rettype unmodified even if it's polymorphic.  This should
2131
 * never occur for user-declared functions, because CREATE FUNCTION prevents
2132
 * it.  But it does happen for some built-in functions, such as array_in().
2133
 */
2134
Oid
2135
enforce_generic_type_consistency(const Oid *actual_arg_types,
2136
                 Oid *declared_arg_types,
2137
                 int nargs,
2138
                 Oid rettype,
2139
                 bool allow_poly)
2140
0
{
2141
0
  bool    have_poly_anycompatible = false;
2142
0
  bool    have_poly_unknowns = false;
2143
0
  Oid     elem_typeid = InvalidOid;
2144
0
  Oid     array_typeid = InvalidOid;
2145
0
  Oid     range_typeid = InvalidOid;
2146
0
  Oid     multirange_typeid = InvalidOid;
2147
0
  Oid     anycompatible_typeid = InvalidOid;
2148
0
  Oid     anycompatible_array_typeid = InvalidOid;
2149
0
  Oid     anycompatible_range_typeid = InvalidOid;
2150
0
  Oid     anycompatible_range_typelem = InvalidOid;
2151
0
  Oid     anycompatible_multirange_typeid = InvalidOid;
2152
0
  Oid     anycompatible_multirange_typelem = InvalidOid;
2153
0
  bool    have_anynonarray = (rettype == ANYNONARRAYOID);
2154
0
  bool    have_anyenum = (rettype == ANYENUMOID);
2155
0
  bool    have_anymultirange = (rettype == ANYMULTIRANGEOID);
2156
0
  bool    have_anycompatible_nonarray = (rettype == ANYCOMPATIBLENONARRAYOID);
2157
0
  bool    have_anycompatible_array = (rettype == ANYCOMPATIBLEARRAYOID);
2158
0
  bool    have_anycompatible_range = (rettype == ANYCOMPATIBLERANGEOID);
2159
0
  bool    have_anycompatible_multirange = (rettype == ANYCOMPATIBLEMULTIRANGEOID);
2160
0
  int     n_poly_args = 0;  /* this counts all family-1 arguments */
2161
0
  int     n_anycompatible_args = 0; /* this counts only non-unknowns */
2162
0
  Oid     anycompatible_actual_types[FUNC_MAX_ARGS];
2163
2164
  /*
2165
   * Loop through the arguments to see if we have any that are polymorphic.
2166
   * If so, require the actual types to be consistent.
2167
   */
2168
0
  Assert(nargs <= FUNC_MAX_ARGS);
2169
0
  for (int j = 0; j < nargs; j++)
2170
0
  {
2171
0
    Oid     decl_type = declared_arg_types[j];
2172
0
    Oid     actual_type = actual_arg_types[j];
2173
2174
0
    if (decl_type == ANYELEMENTOID ||
2175
0
      decl_type == ANYNONARRAYOID ||
2176
0
      decl_type == ANYENUMOID)
2177
0
    {
2178
0
      n_poly_args++;
2179
0
      if (decl_type == ANYNONARRAYOID)
2180
0
        have_anynonarray = true;
2181
0
      else if (decl_type == ANYENUMOID)
2182
0
        have_anyenum = true;
2183
0
      if (actual_type == UNKNOWNOID)
2184
0
      {
2185
0
        have_poly_unknowns = true;
2186
0
        continue;
2187
0
      }
2188
0
      if (allow_poly && decl_type == actual_type)
2189
0
        continue;   /* no new information here */
2190
0
      if (OidIsValid(elem_typeid) && actual_type != elem_typeid)
2191
0
        ereport(ERROR,
2192
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2193
0
             errmsg("arguments declared \"%s\" are not all alike", "anyelement"),
2194
0
             errdetail("%s versus %s",
2195
0
                   format_type_be(elem_typeid),
2196
0
                   format_type_be(actual_type))));
2197
0
      elem_typeid = actual_type;
2198
0
    }
2199
0
    else if (decl_type == ANYARRAYOID)
2200
0
    {
2201
0
      n_poly_args++;
2202
0
      if (actual_type == UNKNOWNOID)
2203
0
      {
2204
0
        have_poly_unknowns = true;
2205
0
        continue;
2206
0
      }
2207
0
      if (allow_poly && decl_type == actual_type)
2208
0
        continue;   /* no new information here */
2209
0
      actual_type = getBaseType(actual_type); /* flatten domains */
2210
0
      if (OidIsValid(array_typeid) && actual_type != array_typeid)
2211
0
        ereport(ERROR,
2212
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2213
0
             errmsg("arguments declared \"%s\" are not all alike", "anyarray"),
2214
0
             errdetail("%s versus %s",
2215
0
                   format_type_be(array_typeid),
2216
0
                   format_type_be(actual_type))));
2217
0
      array_typeid = actual_type;
2218
0
    }
2219
0
    else if (decl_type == ANYRANGEOID)
2220
0
    {
2221
0
      n_poly_args++;
2222
0
      if (actual_type == UNKNOWNOID)
2223
0
      {
2224
0
        have_poly_unknowns = true;
2225
0
        continue;
2226
0
      }
2227
0
      if (allow_poly && decl_type == actual_type)
2228
0
        continue;   /* no new information here */
2229
0
      actual_type = getBaseType(actual_type); /* flatten domains */
2230
0
      if (OidIsValid(range_typeid) && actual_type != range_typeid)
2231
0
        ereport(ERROR,
2232
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2233
0
             errmsg("arguments declared \"%s\" are not all alike", "anyrange"),
2234
0
             errdetail("%s versus %s",
2235
0
                   format_type_be(range_typeid),
2236
0
                   format_type_be(actual_type))));
2237
0
      range_typeid = actual_type;
2238
0
    }
2239
0
    else if (decl_type == ANYMULTIRANGEOID)
2240
0
    {
2241
0
      n_poly_args++;
2242
0
      have_anymultirange = true;
2243
0
      if (actual_type == UNKNOWNOID)
2244
0
      {
2245
0
        have_poly_unknowns = true;
2246
0
        continue;
2247
0
      }
2248
0
      if (allow_poly && decl_type == actual_type)
2249
0
        continue;   /* no new information here */
2250
0
      actual_type = getBaseType(actual_type); /* flatten domains */
2251
0
      if (OidIsValid(multirange_typeid) && actual_type != multirange_typeid)
2252
0
        ereport(ERROR,
2253
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2254
0
             errmsg("arguments declared \"%s\" are not all alike", "anymultirange"),
2255
0
             errdetail("%s versus %s",
2256
0
                   format_type_be(multirange_typeid),
2257
0
                   format_type_be(actual_type))));
2258
0
      multirange_typeid = actual_type;
2259
0
    }
2260
0
    else if (decl_type == ANYCOMPATIBLEOID ||
2261
0
         decl_type == ANYCOMPATIBLENONARRAYOID)
2262
0
    {
2263
0
      have_poly_anycompatible = true;
2264
0
      if (decl_type == ANYCOMPATIBLENONARRAYOID)
2265
0
        have_anycompatible_nonarray = true;
2266
0
      if (actual_type == UNKNOWNOID)
2267
0
        continue;
2268
0
      if (allow_poly && decl_type == actual_type)
2269
0
        continue;   /* no new information here */
2270
      /* collect the actual types of non-unknown COMPATIBLE args */
2271
0
      anycompatible_actual_types[n_anycompatible_args++] = actual_type;
2272
0
    }
2273
0
    else if (decl_type == ANYCOMPATIBLEARRAYOID)
2274
0
    {
2275
0
      Oid     anycompatible_elem_type;
2276
2277
0
      have_poly_anycompatible = true;
2278
0
      have_anycompatible_array = true;
2279
0
      if (actual_type == UNKNOWNOID)
2280
0
        continue;
2281
0
      if (allow_poly && decl_type == actual_type)
2282
0
        continue;   /* no new information here */
2283
0
      actual_type = getBaseType(actual_type); /* flatten domains */
2284
0
      anycompatible_elem_type = get_element_type(actual_type);
2285
0
      if (!OidIsValid(anycompatible_elem_type))
2286
0
        ereport(ERROR,
2287
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2288
0
             errmsg("argument declared %s is not an array but type %s",
2289
0
                "anycompatiblearray",
2290
0
                format_type_be(actual_type))));
2291
      /* collect the element type for common-supertype choice */
2292
0
      anycompatible_actual_types[n_anycompatible_args++] = anycompatible_elem_type;
2293
0
    }
2294
0
    else if (decl_type == ANYCOMPATIBLERANGEOID)
2295
0
    {
2296
0
      have_poly_anycompatible = true;
2297
0
      have_anycompatible_range = true;
2298
0
      if (actual_type == UNKNOWNOID)
2299
0
        continue;
2300
0
      if (allow_poly && decl_type == actual_type)
2301
0
        continue;   /* no new information here */
2302
0
      actual_type = getBaseType(actual_type); /* flatten domains */
2303
0
      if (OidIsValid(anycompatible_range_typeid))
2304
0
      {
2305
        /* All ANYCOMPATIBLERANGE arguments must be the same type */
2306
0
        if (anycompatible_range_typeid != actual_type)
2307
0
          ereport(ERROR,
2308
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2309
0
               errmsg("arguments declared \"%s\" are not all alike", "anycompatiblerange"),
2310
0
               errdetail("%s versus %s",
2311
0
                     format_type_be(anycompatible_range_typeid),
2312
0
                     format_type_be(actual_type))));
2313
0
      }
2314
0
      else
2315
0
      {
2316
0
        anycompatible_range_typeid = actual_type;
2317
0
        anycompatible_range_typelem = get_range_subtype(actual_type);
2318
0
        if (!OidIsValid(anycompatible_range_typelem))
2319
0
          ereport(ERROR,
2320
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2321
0
               errmsg("argument declared %s is not a range type but type %s",
2322
0
                  "anycompatiblerange",
2323
0
                  format_type_be(actual_type))));
2324
        /* collect the subtype for common-supertype choice */
2325
0
        anycompatible_actual_types[n_anycompatible_args++] = anycompatible_range_typelem;
2326
0
      }
2327
0
    }
2328
0
    else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
2329
0
    {
2330
0
      have_poly_anycompatible = true;
2331
0
      have_anycompatible_multirange = true;
2332
0
      if (actual_type == UNKNOWNOID)
2333
0
        continue;
2334
0
      if (allow_poly && decl_type == actual_type)
2335
0
        continue;   /* no new information here */
2336
0
      actual_type = getBaseType(actual_type); /* flatten domains */
2337
0
      if (OidIsValid(anycompatible_multirange_typeid))
2338
0
      {
2339
        /* All ANYCOMPATIBLEMULTIRANGE arguments must be the same type */
2340
0
        if (anycompatible_multirange_typeid != actual_type)
2341
0
          ereport(ERROR,
2342
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2343
0
               errmsg("arguments declared \"%s\" are not all alike", "anycompatiblemultirange"),
2344
0
               errdetail("%s versus %s",
2345
0
                     format_type_be(anycompatible_multirange_typeid),
2346
0
                     format_type_be(actual_type))));
2347
0
      }
2348
0
      else
2349
0
      {
2350
0
        anycompatible_multirange_typeid = actual_type;
2351
0
        anycompatible_multirange_typelem = get_multirange_range(actual_type);
2352
0
        if (!OidIsValid(anycompatible_multirange_typelem))
2353
0
          ereport(ERROR,
2354
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2355
0
               errmsg("argument declared %s is not a multirange type but type %s",
2356
0
                  "anycompatiblemultirange",
2357
0
                  format_type_be(actual_type))));
2358
        /* we'll consider the subtype below */
2359
0
      }
2360
0
    }
2361
0
  }
2362
2363
  /*
2364
   * Fast Track: if none of the arguments are polymorphic, return the
2365
   * unmodified rettype.  Not our job to resolve it if it's polymorphic.
2366
   */
2367
0
  if (n_poly_args == 0 && !have_poly_anycompatible)
2368
0
    return rettype;
2369
2370
  /* Check matching of family-1 polymorphic arguments, if any */
2371
0
  if (n_poly_args)
2372
0
  {
2373
    /* Get the element type based on the array type, if we have one */
2374
0
    if (OidIsValid(array_typeid))
2375
0
    {
2376
0
      Oid     array_typelem;
2377
2378
0
      if (array_typeid == ANYARRAYOID)
2379
0
      {
2380
        /*
2381
         * Special case for matching ANYARRAY input to an ANYARRAY
2382
         * argument: allow it iff no other arguments are family-1
2383
         * polymorphics (otherwise we couldn't be sure whether the
2384
         * array element type matches up) and the result type doesn't
2385
         * require us to infer a specific element type.
2386
         */
2387
0
        if (n_poly_args != 1 ||
2388
0
          (rettype != ANYARRAYOID &&
2389
0
           IsPolymorphicTypeFamily1(rettype)))
2390
0
          ereport(ERROR,
2391
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2392
0
               errmsg("cannot determine element type of \"anyarray\" argument")));
2393
0
        array_typelem = ANYELEMENTOID;
2394
0
      }
2395
0
      else
2396
0
      {
2397
0
        array_typelem = get_element_type(array_typeid);
2398
0
        if (!OidIsValid(array_typelem))
2399
0
          ereport(ERROR,
2400
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2401
0
               errmsg("argument declared %s is not an array but type %s",
2402
0
                  "anyarray", format_type_be(array_typeid))));
2403
0
      }
2404
2405
0
      if (!OidIsValid(elem_typeid))
2406
0
      {
2407
        /*
2408
         * if we don't have an element type yet, use the one we just
2409
         * got
2410
         */
2411
0
        elem_typeid = array_typelem;
2412
0
      }
2413
0
      else if (array_typelem != elem_typeid)
2414
0
      {
2415
        /* otherwise, they better match */
2416
0
        ereport(ERROR,
2417
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2418
0
             errmsg("argument declared %s is not consistent with argument declared %s",
2419
0
                "anyarray", "anyelement"),
2420
0
             errdetail("%s versus %s",
2421
0
                   format_type_be(array_typeid),
2422
0
                   format_type_be(elem_typeid))));
2423
0
      }
2424
0
    }
2425
2426
    /* Deduce range type from multirange type, or vice versa */
2427
0
    if (OidIsValid(multirange_typeid))
2428
0
    {
2429
0
      Oid     multirange_typelem;
2430
2431
0
      multirange_typelem = get_multirange_range(multirange_typeid);
2432
0
      if (!OidIsValid(multirange_typelem))
2433
0
        ereport(ERROR,
2434
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2435
0
             errmsg("argument declared %s is not a multirange type but type %s",
2436
0
                "anymultirange",
2437
0
                format_type_be(multirange_typeid))));
2438
2439
0
      if (!OidIsValid(range_typeid))
2440
0
      {
2441
        /* if we don't have a range type yet, use the one we just got */
2442
0
        range_typeid = multirange_typelem;
2443
0
      }
2444
0
      else if (multirange_typelem != range_typeid)
2445
0
      {
2446
        /* otherwise, they better match */
2447
0
        ereport(ERROR,
2448
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2449
0
             errmsg("argument declared %s is not consistent with argument declared %s",
2450
0
                "anymultirange", "anyrange"),
2451
0
             errdetail("%s versus %s",
2452
0
                   format_type_be(multirange_typeid),
2453
0
                   format_type_be(range_typeid))));
2454
0
      }
2455
0
    }
2456
0
    else if (have_anymultirange && OidIsValid(range_typeid))
2457
0
    {
2458
0
      multirange_typeid = get_range_multirange(range_typeid);
2459
      /* We'll complain below if that didn't work */
2460
0
    }
2461
2462
    /* Get the element type based on the range type, if we have one */
2463
0
    if (OidIsValid(range_typeid))
2464
0
    {
2465
0
      Oid     range_typelem;
2466
2467
0
      range_typelem = get_range_subtype(range_typeid);
2468
0
      if (!OidIsValid(range_typelem))
2469
0
        ereport(ERROR,
2470
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2471
0
             errmsg("argument declared %s is not a range type but type %s",
2472
0
                "anyrange",
2473
0
                format_type_be(range_typeid))));
2474
2475
0
      if (!OidIsValid(elem_typeid))
2476
0
      {
2477
        /*
2478
         * if we don't have an element type yet, use the one we just
2479
         * got
2480
         */
2481
0
        elem_typeid = range_typelem;
2482
0
      }
2483
0
      else if (range_typelem != elem_typeid)
2484
0
      {
2485
        /* otherwise, they better match */
2486
0
        ereport(ERROR,
2487
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2488
0
             errmsg("argument declared %s is not consistent with argument declared %s",
2489
0
                "anyrange", "anyelement"),
2490
0
             errdetail("%s versus %s",
2491
0
                   format_type_be(range_typeid),
2492
0
                   format_type_be(elem_typeid))));
2493
0
      }
2494
0
    }
2495
2496
0
    if (!OidIsValid(elem_typeid))
2497
0
    {
2498
0
      if (allow_poly)
2499
0
      {
2500
0
        elem_typeid = ANYELEMENTOID;
2501
0
        array_typeid = ANYARRAYOID;
2502
0
        range_typeid = ANYRANGEOID;
2503
0
        multirange_typeid = ANYMULTIRANGEOID;
2504
0
      }
2505
0
      else
2506
0
      {
2507
        /*
2508
         * Only way to get here is if all the family-1 polymorphic
2509
         * arguments have UNKNOWN inputs.
2510
         */
2511
0
        ereport(ERROR,
2512
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2513
0
             errmsg("could not determine polymorphic type because input has type %s",
2514
0
                "unknown")));
2515
0
      }
2516
0
    }
2517
2518
0
    if (have_anynonarray && elem_typeid != ANYELEMENTOID)
2519
0
    {
2520
      /*
2521
       * require the element type to not be an array or domain over
2522
       * array
2523
       */
2524
0
      if (type_is_array_domain(elem_typeid))
2525
0
        ereport(ERROR,
2526
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2527
0
             errmsg("type matched to anynonarray is an array type: %s",
2528
0
                format_type_be(elem_typeid))));
2529
0
    }
2530
2531
0
    if (have_anyenum && elem_typeid != ANYELEMENTOID)
2532
0
    {
2533
      /* require the element type to be an enum */
2534
0
      if (!type_is_enum(elem_typeid))
2535
0
        ereport(ERROR,
2536
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2537
0
             errmsg("type matched to anyenum is not an enum type: %s",
2538
0
                format_type_be(elem_typeid))));
2539
0
    }
2540
0
  }
2541
2542
  /* Check matching of family-2 polymorphic arguments, if any */
2543
0
  if (have_poly_anycompatible)
2544
0
  {
2545
    /* Deduce range type from multirange type, or vice versa */
2546
0
    if (OidIsValid(anycompatible_multirange_typeid))
2547
0
    {
2548
0
      if (OidIsValid(anycompatible_range_typeid))
2549
0
      {
2550
0
        if (anycompatible_multirange_typelem !=
2551
0
          anycompatible_range_typeid)
2552
0
          ereport(ERROR,
2553
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2554
0
               errmsg("argument declared %s is not consistent with argument declared %s",
2555
0
                  "anycompatiblemultirange",
2556
0
                  "anycompatiblerange"),
2557
0
               errdetail("%s versus %s",
2558
0
                     format_type_be(anycompatible_multirange_typeid),
2559
0
                     format_type_be(anycompatible_range_typeid))));
2560
0
      }
2561
0
      else
2562
0
      {
2563
0
        anycompatible_range_typeid = anycompatible_multirange_typelem;
2564
0
        anycompatible_range_typelem = get_range_subtype(anycompatible_range_typeid);
2565
0
        if (!OidIsValid(anycompatible_range_typelem))
2566
0
          ereport(ERROR,
2567
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2568
0
               errmsg("argument declared %s is not a multirange type but type %s",
2569
0
                  "anycompatiblemultirange",
2570
0
                  format_type_be(anycompatible_multirange_typeid))));
2571
        /* this enables element type matching check below */
2572
0
        have_anycompatible_range = true;
2573
        /* collect the subtype for common-supertype choice */
2574
0
        anycompatible_actual_types[n_anycompatible_args++] =
2575
0
          anycompatible_range_typelem;
2576
0
      }
2577
0
    }
2578
0
    else if (have_anycompatible_multirange &&
2579
0
         OidIsValid(anycompatible_range_typeid))
2580
0
    {
2581
0
      anycompatible_multirange_typeid = get_range_multirange(anycompatible_range_typeid);
2582
      /* We'll complain below if that didn't work */
2583
0
    }
2584
2585
0
    if (n_anycompatible_args > 0)
2586
0
    {
2587
0
      anycompatible_typeid =
2588
0
        select_common_type_from_oids(n_anycompatible_args,
2589
0
                       anycompatible_actual_types,
2590
0
                       false);
2591
2592
      /* We have to verify that the selected type actually works */
2593
0
      if (!verify_common_type_from_oids(anycompatible_typeid,
2594
0
                        n_anycompatible_args,
2595
0
                        anycompatible_actual_types))
2596
0
        ereport(ERROR,
2597
0
            (errcode(ERRCODE_DATATYPE_MISMATCH),
2598
0
             errmsg("arguments of anycompatible family cannot be cast to a common type")));
2599
2600
0
      if (have_anycompatible_array)
2601
0
      {
2602
0
        anycompatible_array_typeid = get_array_type(anycompatible_typeid);
2603
0
        if (!OidIsValid(anycompatible_array_typeid))
2604
0
          ereport(ERROR,
2605
0
              (errcode(ERRCODE_UNDEFINED_OBJECT),
2606
0
               errmsg("could not find array type for data type %s",
2607
0
                  format_type_be(anycompatible_typeid))));
2608
0
      }
2609
2610
0
      if (have_anycompatible_range)
2611
0
      {
2612
        /* we can't infer a range type from the others */
2613
0
        if (!OidIsValid(anycompatible_range_typeid))
2614
0
          ereport(ERROR,
2615
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2616
0
               errmsg("could not determine polymorphic type %s because input has type %s",
2617
0
                  "anycompatiblerange", "unknown")));
2618
2619
        /*
2620
         * the anycompatible type must exactly match the range element
2621
         * type
2622
         */
2623
0
        if (anycompatible_range_typelem != anycompatible_typeid)
2624
0
          ereport(ERROR,
2625
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2626
0
               errmsg("anycompatiblerange type %s does not match anycompatible type %s",
2627
0
                  format_type_be(anycompatible_range_typeid),
2628
0
                  format_type_be(anycompatible_typeid))));
2629
0
      }
2630
2631
0
      if (have_anycompatible_multirange)
2632
0
      {
2633
        /* we can't infer a multirange type from the others */
2634
0
        if (!OidIsValid(anycompatible_multirange_typeid))
2635
0
          ereport(ERROR,
2636
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2637
0
               errmsg("could not determine polymorphic type %s because input has type %s",
2638
0
                  "anycompatiblemultirange", "unknown")));
2639
2640
        /*
2641
         * the anycompatible type must exactly match the multirange
2642
         * element type
2643
         */
2644
0
        if (anycompatible_range_typelem != anycompatible_typeid)
2645
0
          ereport(ERROR,
2646
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2647
0
               errmsg("anycompatiblemultirange type %s does not match anycompatible type %s",
2648
0
                  format_type_be(anycompatible_multirange_typeid),
2649
0
                  format_type_be(anycompatible_typeid))));
2650
0
      }
2651
2652
0
      if (have_anycompatible_nonarray)
2653
0
      {
2654
        /*
2655
         * require the element type to not be an array or domain over
2656
         * array
2657
         */
2658
0
        if (type_is_array_domain(anycompatible_typeid))
2659
0
          ereport(ERROR,
2660
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2661
0
               errmsg("type matched to anycompatiblenonarray is an array type: %s",
2662
0
                  format_type_be(anycompatible_typeid))));
2663
0
      }
2664
0
    }
2665
0
    else
2666
0
    {
2667
0
      if (allow_poly)
2668
0
      {
2669
0
        anycompatible_typeid = ANYCOMPATIBLEOID;
2670
0
        anycompatible_array_typeid = ANYCOMPATIBLEARRAYOID;
2671
0
        anycompatible_range_typeid = ANYCOMPATIBLERANGEOID;
2672
0
        anycompatible_multirange_typeid = ANYCOMPATIBLEMULTIRANGEOID;
2673
0
      }
2674
0
      else
2675
0
      {
2676
        /*
2677
         * Only way to get here is if all the family-2 polymorphic
2678
         * arguments have UNKNOWN inputs.  Resolve to TEXT as
2679
         * select_common_type() would do.  That doesn't license us to
2680
         * use TEXTRANGE or TEXTMULTIRANGE, though.
2681
         */
2682
0
        anycompatible_typeid = TEXTOID;
2683
0
        anycompatible_array_typeid = TEXTARRAYOID;
2684
0
        if (have_anycompatible_range)
2685
0
          ereport(ERROR,
2686
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2687
0
               errmsg("could not determine polymorphic type %s because input has type %s",
2688
0
                  "anycompatiblerange", "unknown")));
2689
0
        if (have_anycompatible_multirange)
2690
0
          ereport(ERROR,
2691
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2692
0
               errmsg("could not determine polymorphic type %s because input has type %s",
2693
0
                  "anycompatiblemultirange", "unknown")));
2694
0
      }
2695
0
    }
2696
2697
    /* replace family-2 polymorphic types by selected types */
2698
0
    for (int j = 0; j < nargs; j++)
2699
0
    {
2700
0
      Oid     decl_type = declared_arg_types[j];
2701
2702
0
      if (decl_type == ANYCOMPATIBLEOID ||
2703
0
        decl_type == ANYCOMPATIBLENONARRAYOID)
2704
0
        declared_arg_types[j] = anycompatible_typeid;
2705
0
      else if (decl_type == ANYCOMPATIBLEARRAYOID)
2706
0
        declared_arg_types[j] = anycompatible_array_typeid;
2707
0
      else if (decl_type == ANYCOMPATIBLERANGEOID)
2708
0
        declared_arg_types[j] = anycompatible_range_typeid;
2709
0
      else if (decl_type == ANYCOMPATIBLEMULTIRANGEOID)
2710
0
        declared_arg_types[j] = anycompatible_multirange_typeid;
2711
0
    }
2712
0
  }
2713
2714
  /*
2715
   * If we had any UNKNOWN inputs for family-1 polymorphic arguments,
2716
   * re-scan to assign correct types to them.
2717
   *
2718
   * Note: we don't have to consider unknown inputs that were matched to
2719
   * family-2 polymorphic arguments, because we forcibly updated their
2720
   * declared_arg_types[] positions just above.
2721
   */
2722
0
  if (have_poly_unknowns)
2723
0
  {
2724
0
    for (int j = 0; j < nargs; j++)
2725
0
    {
2726
0
      Oid     decl_type = declared_arg_types[j];
2727
0
      Oid     actual_type = actual_arg_types[j];
2728
2729
0
      if (actual_type != UNKNOWNOID)
2730
0
        continue;
2731
2732
0
      if (decl_type == ANYELEMENTOID ||
2733
0
        decl_type == ANYNONARRAYOID ||
2734
0
        decl_type == ANYENUMOID)
2735
0
        declared_arg_types[j] = elem_typeid;
2736
0
      else if (decl_type == ANYARRAYOID)
2737
0
      {
2738
0
        if (!OidIsValid(array_typeid))
2739
0
        {
2740
0
          array_typeid = get_array_type(elem_typeid);
2741
0
          if (!OidIsValid(array_typeid))
2742
0
            ereport(ERROR,
2743
0
                (errcode(ERRCODE_UNDEFINED_OBJECT),
2744
0
                 errmsg("could not find array type for data type %s",
2745
0
                    format_type_be(elem_typeid))));
2746
0
        }
2747
0
        declared_arg_types[j] = array_typeid;
2748
0
      }
2749
0
      else if (decl_type == ANYRANGEOID)
2750
0
      {
2751
0
        if (!OidIsValid(range_typeid))
2752
0
        {
2753
          /* we can't infer a range type from the others */
2754
0
          ereport(ERROR,
2755
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2756
0
               errmsg("could not determine polymorphic type %s because input has type %s",
2757
0
                  "anyrange", "unknown")));
2758
0
        }
2759
0
        declared_arg_types[j] = range_typeid;
2760
0
      }
2761
0
      else if (decl_type == ANYMULTIRANGEOID)
2762
0
      {
2763
0
        if (!OidIsValid(multirange_typeid))
2764
0
        {
2765
          /* we can't infer a multirange type from the others */
2766
0
          ereport(ERROR,
2767
0
              (errcode(ERRCODE_DATATYPE_MISMATCH),
2768
0
               errmsg("could not determine polymorphic type %s because input has type %s",
2769
0
                  "anymultirange", "unknown")));
2770
0
        }
2771
0
        declared_arg_types[j] = multirange_typeid;
2772
0
      }
2773
0
    }
2774
0
  }
2775
2776
  /* if we return ANYELEMENT use the appropriate argument type */
2777
0
  if (rettype == ANYELEMENTOID ||
2778
0
    rettype == ANYNONARRAYOID ||
2779
0
    rettype == ANYENUMOID)
2780
0
    return elem_typeid;
2781
2782
  /* if we return ANYARRAY use the appropriate argument type */
2783
0
  if (rettype == ANYARRAYOID)
2784
0
  {
2785
0
    if (!OidIsValid(array_typeid))
2786
0
    {
2787
0
      array_typeid = get_array_type(elem_typeid);
2788
0
      if (!OidIsValid(array_typeid))
2789
0
        ereport(ERROR,
2790
0
            (errcode(ERRCODE_UNDEFINED_OBJECT),
2791
0
             errmsg("could not find array type for data type %s",
2792
0
                format_type_be(elem_typeid))));
2793
0
    }
2794
0
    return array_typeid;
2795
0
  }
2796
2797
  /* if we return ANYRANGE use the appropriate argument type */
2798
0
  if (rettype == ANYRANGEOID)
2799
0
  {
2800
    /* this error is unreachable if the function signature is valid: */
2801
0
    if (!OidIsValid(range_typeid))
2802
0
      ereport(ERROR,
2803
0
          (errcode(ERRCODE_DATATYPE_MISMATCH),
2804
0
           errmsg_internal("could not determine polymorphic type %s because input has type %s",
2805
0
                   "anyrange", "unknown")));
2806
0
    return range_typeid;
2807
0
  }
2808
2809
  /* if we return ANYMULTIRANGE use the appropriate argument type */
2810
0
  if (rettype == ANYMULTIRANGEOID)
2811
0
  {
2812
    /* this error is unreachable if the function signature is valid: */
2813
0
    if (!OidIsValid(multirange_typeid))
2814
0
      ereport(ERROR,
2815
0
          (errcode(ERRCODE_DATATYPE_MISMATCH),
2816
0
           errmsg_internal("could not determine polymorphic type %s because input has type %s",
2817
0
                   "anymultirange", "unknown")));
2818
0
    return multirange_typeid;
2819
0
  }
2820
2821
  /* if we return ANYCOMPATIBLE use the appropriate type */
2822
0
  if (rettype == ANYCOMPATIBLEOID ||
2823
0
    rettype == ANYCOMPATIBLENONARRAYOID)
2824
0
  {
2825
    /* this error is unreachable if the function signature is valid: */
2826
0
    if (!OidIsValid(anycompatible_typeid))
2827
0
      ereport(ERROR,
2828
0
          (errcode(ERRCODE_DATATYPE_MISMATCH),
2829
0
           errmsg_internal("could not identify anycompatible type")));
2830
0
    return anycompatible_typeid;
2831
0
  }
2832
2833
  /* if we return ANYCOMPATIBLEARRAY use the appropriate type */
2834
0
  if (rettype == ANYCOMPATIBLEARRAYOID)
2835
0
  {
2836
    /* this error is unreachable if the function signature is valid: */
2837
0
    if (!OidIsValid(anycompatible_array_typeid))
2838
0
      ereport(ERROR,
2839
0
          (errcode(ERRCODE_DATATYPE_MISMATCH),
2840
0
           errmsg_internal("could not identify anycompatiblearray type")));
2841
0
    return anycompatible_array_typeid;
2842
0
  }
2843
2844
  /* if we return ANYCOMPATIBLERANGE use the appropriate argument type */
2845
0
  if (rettype == ANYCOMPATIBLERANGEOID)
2846
0
  {
2847
    /* this error is unreachable if the function signature is valid: */
2848
0
    if (!OidIsValid(anycompatible_range_typeid))
2849
0
      ereport(ERROR,
2850
0
          (errcode(ERRCODE_DATATYPE_MISMATCH),
2851
0
           errmsg_internal("could not identify anycompatiblerange type")));
2852
0
    return anycompatible_range_typeid;
2853
0
  }
2854
2855
  /* if we return ANYCOMPATIBLEMULTIRANGE use the appropriate argument type */
2856
0
  if (rettype == ANYCOMPATIBLEMULTIRANGEOID)
2857
0
  {
2858
    /* this error is unreachable if the function signature is valid: */
2859
0
    if (!OidIsValid(anycompatible_multirange_typeid))
2860
0
      ereport(ERROR,
2861
0
          (errcode(ERRCODE_DATATYPE_MISMATCH),
2862
0
           errmsg_internal("could not identify anycompatiblemultirange type")));
2863
0
    return anycompatible_multirange_typeid;
2864
0
  }
2865
2866
  /* we don't return a generic type; send back the original return type */
2867
0
  return rettype;
2868
0
}
2869
2870
/*
2871
 * check_valid_polymorphic_signature()
2872
 *    Is a proposed function signature valid per polymorphism rules?
2873
 *
2874
 * Returns NULL if the signature is valid (either ret_type is not polymorphic,
2875
 * or it can be deduced from the given declared argument types).  Otherwise,
2876
 * returns a palloc'd, already translated errdetail string saying why not.
2877
 */
2878
char *
2879
check_valid_polymorphic_signature(Oid ret_type,
2880
                  const Oid *declared_arg_types,
2881
                  int nargs)
2882
0
{
2883
0
  if (ret_type == ANYRANGEOID || ret_type == ANYMULTIRANGEOID)
2884
0
  {
2885
    /*
2886
     * ANYRANGE and ANYMULTIRANGE require an ANYRANGE or ANYMULTIRANGE
2887
     * input, else we can't tell which of several range types with the
2888
     * same element type to use.
2889
     */
2890
0
    for (int i = 0; i < nargs; i++)
2891
0
    {
2892
0
      if (declared_arg_types[i] == ANYRANGEOID ||
2893
0
        declared_arg_types[i] == ANYMULTIRANGEOID)
2894
0
        return NULL; /* OK */
2895
0
    }
2896
0
    return psprintf(_("A result of type %s requires at least one input of type anyrange or anymultirange."),
2897
0
            format_type_be(ret_type));
2898
0
  }
2899
0
  else if (ret_type == ANYCOMPATIBLERANGEOID || ret_type == ANYCOMPATIBLEMULTIRANGEOID)
2900
0
  {
2901
    /*
2902
     * ANYCOMPATIBLERANGE and ANYCOMPATIBLEMULTIRANGE require an
2903
     * ANYCOMPATIBLERANGE or ANYCOMPATIBLEMULTIRANGE input, else we can't
2904
     * tell which of several range types with the same element type to
2905
     * use.
2906
     */
2907
0
    for (int i = 0; i < nargs; i++)
2908
0
    {
2909
0
      if (declared_arg_types[i] == ANYCOMPATIBLERANGEOID ||
2910
0
        declared_arg_types[i] == ANYCOMPATIBLEMULTIRANGEOID)
2911
0
        return NULL; /* OK */
2912
0
    }
2913
0
    return psprintf(_("A result of type %s requires at least one input of type anycompatiblerange or anycompatiblemultirange."),
2914
0
            format_type_be(ret_type));
2915
0
  }
2916
0
  else if (IsPolymorphicTypeFamily1(ret_type))
2917
0
  {
2918
    /* Otherwise, any family-1 type can be deduced from any other */
2919
0
    for (int i = 0; i < nargs; i++)
2920
0
    {
2921
0
      if (IsPolymorphicTypeFamily1(declared_arg_types[i]))
2922
0
        return NULL; /* OK */
2923
0
    }
2924
    /* Keep this list in sync with IsPolymorphicTypeFamily1! */
2925
0
    return psprintf(_("A result of type %s requires at least one input of type anyelement, anyarray, anynonarray, anyenum, anyrange, or anymultirange."),
2926
0
            format_type_be(ret_type));
2927
0
  }
2928
0
  else if (IsPolymorphicTypeFamily2(ret_type))
2929
0
  {
2930
    /* Otherwise, any family-2 type can be deduced from any other */
2931
0
    for (int i = 0; i < nargs; i++)
2932
0
    {
2933
0
      if (IsPolymorphicTypeFamily2(declared_arg_types[i]))
2934
0
        return NULL; /* OK */
2935
0
    }
2936
    /* Keep this list in sync with IsPolymorphicTypeFamily2! */
2937
0
    return psprintf(_("A result of type %s requires at least one input of type anycompatible, anycompatiblearray, anycompatiblenonarray, anycompatiblerange, or anycompatiblemultirange."),
2938
0
            format_type_be(ret_type));
2939
0
  }
2940
0
  else
2941
0
    return NULL;     /* OK, ret_type is not polymorphic */
2942
0
}
2943
2944
/*
2945
 * check_valid_internal_signature()
2946
 *    Is a proposed function signature valid per INTERNAL safety rules?
2947
 *
2948
 * Returns NULL if OK, or a suitable error message if ret_type is INTERNAL but
2949
 * none of the declared arg types are.  (It's unsafe to create such a function
2950
 * since it would allow invocation of INTERNAL-consuming functions directly
2951
 * from SQL.)  It's overkill to return the error detail message, since there
2952
 * is only one possibility, but we do it like this to keep the API similar to
2953
 * check_valid_polymorphic_signature().
2954
 */
2955
char *
2956
check_valid_internal_signature(Oid ret_type,
2957
                 const Oid *declared_arg_types,
2958
                 int nargs)
2959
0
{
2960
0
  if (ret_type == INTERNALOID)
2961
0
  {
2962
0
    for (int i = 0; i < nargs; i++)
2963
0
    {
2964
0
      if (declared_arg_types[i] == ret_type)
2965
0
        return NULL; /* OK */
2966
0
    }
2967
0
    return pstrdup(_("A result of type internal requires at least one input of type internal."));
2968
0
  }
2969
0
  else
2970
0
    return NULL;     /* OK, ret_type is not INTERNAL */
2971
0
}
2972
2973
2974
/*
2975
 * TypeCategory()
2976
 *    Assign a category to the specified type OID.
2977
 *
2978
 * NB: this must not return TYPCATEGORY_INVALID.
2979
 */
2980
TYPCATEGORY
2981
TypeCategory(Oid type)
2982
0
{
2983
0
  char    typcategory;
2984
0
  bool    typispreferred;
2985
2986
0
  get_type_category_preferred(type, &typcategory, &typispreferred);
2987
0
  Assert(typcategory != TYPCATEGORY_INVALID);
2988
0
  return (TYPCATEGORY) typcategory;
2989
0
}
2990
2991
2992
/*
2993
 * IsPreferredType()
2994
 *    Check if this type is a preferred type for the given category.
2995
 *
2996
 * If category is TYPCATEGORY_INVALID, then we'll return true for preferred
2997
 * types of any category; otherwise, only for preferred types of that
2998
 * category.
2999
 */
3000
bool
3001
IsPreferredType(TYPCATEGORY category, Oid type)
3002
0
{
3003
0
  char    typcategory;
3004
0
  bool    typispreferred;
3005
3006
0
  get_type_category_preferred(type, &typcategory, &typispreferred);
3007
0
  if (category == typcategory || category == TYPCATEGORY_INVALID)
3008
0
    return typispreferred;
3009
0
  else
3010
0
    return false;
3011
0
}
3012
3013
3014
/*
3015
 * IsBinaryCoercible()
3016
 *    Check if srctype is binary-coercible to targettype.
3017
 *
3018
 * This notion allows us to cheat and directly exchange values without
3019
 * going through the trouble of calling a conversion function.  Note that
3020
 * in general, this should only be an implementation shortcut.  Before 7.4,
3021
 * this was also used as a heuristic for resolving overloaded functions and
3022
 * operators, but that's basically a bad idea.
3023
 *
3024
 * As of 7.3, binary coercibility isn't hardwired into the code anymore.
3025
 * We consider two types binary-coercible if there is an implicitly
3026
 * invokable, no-function-needed pg_cast entry.  Also, a domain is always
3027
 * binary-coercible to its base type, though *not* vice versa (in the other
3028
 * direction, one must apply domain constraint checks before accepting the
3029
 * value as legitimate).  We also need to special-case various polymorphic
3030
 * types.
3031
 *
3032
 * This function replaces IsBinaryCompatible(), which was an inherently
3033
 * symmetric test.  Since the pg_cast entries aren't necessarily symmetric,
3034
 * the order of the operands is now significant.
3035
 */
3036
bool
3037
IsBinaryCoercible(Oid srctype, Oid targettype)
3038
0
{
3039
0
  Oid     castoid;
3040
3041
0
  return IsBinaryCoercibleWithCast(srctype, targettype, &castoid);
3042
0
}
3043
3044
/*
3045
 * IsBinaryCoercibleWithCast()
3046
 *    Check if srctype is binary-coercible to targettype.
3047
 *
3048
 * This variant also returns the OID of the pg_cast entry if one is involved.
3049
 * *castoid is set to InvalidOid if no binary-coercible cast exists, or if
3050
 * there is a hard-wired rule for it rather than a pg_cast entry.
3051
 */
3052
bool
3053
IsBinaryCoercibleWithCast(Oid srctype, Oid targettype,
3054
              Oid *castoid)
3055
0
{
3056
0
  HeapTuple tuple;
3057
0
  Form_pg_cast castForm;
3058
0
  bool    result;
3059
3060
0
  *castoid = InvalidOid;
3061
3062
  /* Fast path if same type */
3063
0
  if (srctype == targettype)
3064
0
    return true;
3065
3066
  /* Anything is coercible to ANY or ANYELEMENT or ANYCOMPATIBLE */
3067
0
  if (targettype == ANYOID || targettype == ANYELEMENTOID ||
3068
0
    targettype == ANYCOMPATIBLEOID)
3069
0
    return true;
3070
3071
  /* If srctype is a domain, reduce to its base type */
3072
0
  if (OidIsValid(srctype))
3073
0
    srctype = getBaseType(srctype);
3074
3075
  /* Somewhat-fast path for domain -> base type case */
3076
0
  if (srctype == targettype)
3077
0
    return true;
3078
3079
  /* Also accept any array type as coercible to ANY[COMPATIBLE]ARRAY */
3080
0
  if (targettype == ANYARRAYOID || targettype == ANYCOMPATIBLEARRAYOID)
3081
0
    if (type_is_array(srctype))
3082
0
      return true;
3083
3084
  /* Also accept any non-array type as coercible to ANY[COMPATIBLE]NONARRAY */
3085
0
  if (targettype == ANYNONARRAYOID || targettype == ANYCOMPATIBLENONARRAYOID)
3086
0
    if (!type_is_array(srctype))
3087
0
      return true;
3088
3089
  /* Also accept any enum type as coercible to ANYENUM */
3090
0
  if (targettype == ANYENUMOID)
3091
0
    if (type_is_enum(srctype))
3092
0
      return true;
3093
3094
  /* Also accept any range type as coercible to ANY[COMPATIBLE]RANGE */
3095
0
  if (targettype == ANYRANGEOID || targettype == ANYCOMPATIBLERANGEOID)
3096
0
    if (type_is_range(srctype))
3097
0
      return true;
3098
3099
  /* Also, any multirange type is coercible to ANY[COMPATIBLE]MULTIRANGE */
3100
0
  if (targettype == ANYMULTIRANGEOID || targettype == ANYCOMPATIBLEMULTIRANGEOID)
3101
0
    if (type_is_multirange(srctype))
3102
0
      return true;
3103
3104
  /* Also accept any composite type as coercible to RECORD */
3105
0
  if (targettype == RECORDOID)
3106
0
    if (ISCOMPLEX(srctype))
3107
0
      return true;
3108
3109
  /* Also accept any composite array type as coercible to RECORD[] */
3110
0
  if (targettype == RECORDARRAYOID)
3111
0
    if (is_complex_array(srctype))
3112
0
      return true;
3113
3114
  /* Else look in pg_cast */
3115
0
  tuple = SearchSysCache2(CASTSOURCETARGET,
3116
0
              ObjectIdGetDatum(srctype),
3117
0
              ObjectIdGetDatum(targettype));
3118
0
  if (!HeapTupleIsValid(tuple))
3119
0
    return false;     /* no cast */
3120
0
  castForm = (Form_pg_cast) GETSTRUCT(tuple);
3121
3122
0
  result = (castForm->castmethod == COERCION_METHOD_BINARY &&
3123
0
        castForm->castcontext == COERCION_CODE_IMPLICIT);
3124
3125
0
  if (result)
3126
0
    *castoid = castForm->oid;
3127
3128
0
  ReleaseSysCache(tuple);
3129
3130
0
  return result;
3131
0
}
3132
3133
3134
/*
3135
 * find_coercion_pathway
3136
 *    Look for a coercion pathway between two types.
3137
 *
3138
 * Currently, this deals only with scalar-type cases; it does not consider
3139
 * polymorphic types nor casts between composite types.  (Perhaps fold
3140
 * those in someday?)
3141
 *
3142
 * ccontext determines the set of available casts.
3143
 *
3144
 * The possible result codes are:
3145
 *  COERCION_PATH_NONE: failed to find any coercion pathway
3146
 *        *funcid is set to InvalidOid
3147
 *  COERCION_PATH_FUNC: apply the coercion function returned in *funcid
3148
 *  COERCION_PATH_RELABELTYPE: binary-compatible cast, no function needed
3149
 *        *funcid is set to InvalidOid
3150
 *  COERCION_PATH_ARRAYCOERCE: need an ArrayCoerceExpr node
3151
 *        *funcid is set to InvalidOid
3152
 *  COERCION_PATH_COERCEVIAIO: need a CoerceViaIO node
3153
 *        *funcid is set to InvalidOid
3154
 *
3155
 * Note: COERCION_PATH_RELABELTYPE does not necessarily mean that no work is
3156
 * needed to do the coercion; if the target is a domain then we may need to
3157
 * apply domain constraint checking.  If you want to check for a zero-effort
3158
 * conversion then use IsBinaryCoercible().
3159
 */
3160
CoercionPathType
3161
find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId,
3162
            CoercionContext ccontext,
3163
            Oid *funcid)
3164
0
{
3165
0
  CoercionPathType result = COERCION_PATH_NONE;
3166
0
  HeapTuple tuple;
3167
3168
0
  *funcid = InvalidOid;
3169
3170
  /* Perhaps the types are domains; if so, look at their base types */
3171
0
  if (OidIsValid(sourceTypeId))
3172
0
    sourceTypeId = getBaseType(sourceTypeId);
3173
0
  if (OidIsValid(targetTypeId))
3174
0
    targetTypeId = getBaseType(targetTypeId);
3175
3176
  /* Domains are always coercible to and from their base type */
3177
0
  if (sourceTypeId == targetTypeId)
3178
0
    return COERCION_PATH_RELABELTYPE;
3179
3180
  /* Reject all cases of casting something else to/from "internal" */
3181
0
  if (sourceTypeId == INTERNALOID || targetTypeId == INTERNALOID)
3182
0
    return COERCION_PATH_NONE;
3183
3184
  /* Look in pg_cast */
3185
0
  tuple = SearchSysCache2(CASTSOURCETARGET,
3186
0
              ObjectIdGetDatum(sourceTypeId),
3187
0
              ObjectIdGetDatum(targetTypeId));
3188
3189
0
  if (HeapTupleIsValid(tuple))
3190
0
  {
3191
0
    Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
3192
0
    CoercionContext castcontext;
3193
3194
    /* convert char value for castcontext to CoercionContext enum */
3195
0
    switch (castForm->castcontext)
3196
0
    {
3197
0
      case COERCION_CODE_IMPLICIT:
3198
0
        castcontext = COERCION_IMPLICIT;
3199
0
        break;
3200
0
      case COERCION_CODE_ASSIGNMENT:
3201
0
        castcontext = COERCION_ASSIGNMENT;
3202
0
        break;
3203
0
      case COERCION_CODE_EXPLICIT:
3204
0
        castcontext = COERCION_EXPLICIT;
3205
0
        break;
3206
0
      default:
3207
0
        elog(ERROR, "unrecognized castcontext: %d",
3208
0
           (int) castForm->castcontext);
3209
0
        castcontext = 0;  /* keep compiler quiet */
3210
0
        break;
3211
0
    }
3212
3213
    /* Rely on ordering of enum for correct behavior here */
3214
0
    if (ccontext >= castcontext)
3215
0
    {
3216
0
      switch (castForm->castmethod)
3217
0
      {
3218
0
        case COERCION_METHOD_FUNCTION:
3219
0
          result = COERCION_PATH_FUNC;
3220
0
          *funcid = castForm->castfunc;
3221
0
          break;
3222
0
        case COERCION_METHOD_INOUT:
3223
0
          result = COERCION_PATH_COERCEVIAIO;
3224
0
          break;
3225
0
        case COERCION_METHOD_BINARY:
3226
0
          result = COERCION_PATH_RELABELTYPE;
3227
0
          break;
3228
0
        default:
3229
0
          elog(ERROR, "unrecognized castmethod: %d",
3230
0
             (int) castForm->castmethod);
3231
0
          break;
3232
0
      }
3233
0
    }
3234
3235
0
    ReleaseSysCache(tuple);
3236
0
  }
3237
0
  else
3238
0
  {
3239
    /*
3240
     * If there's no pg_cast entry, perhaps we are dealing with a pair of
3241
     * array types.  If so, and if their element types have a conversion
3242
     * pathway, report that we can coerce with an ArrayCoerceExpr.
3243
     *
3244
     * Hack: disallow coercions to oidvector and int2vector, which
3245
     * otherwise tend to capture coercions that should go to "real" array
3246
     * types.  We want those types to be considered "real" arrays for many
3247
     * purposes, but not this one.  (Also, ArrayCoerceExpr isn't
3248
     * guaranteed to produce an output that meets the restrictions of
3249
     * these datatypes, such as being 1-dimensional.)
3250
     */
3251
0
    if (targetTypeId != OIDVECTOROID && targetTypeId != INT2VECTOROID)
3252
0
    {
3253
0
      Oid     targetElem;
3254
0
      Oid     sourceElem;
3255
3256
0
      if ((targetElem = get_element_type(targetTypeId)) != InvalidOid &&
3257
0
        (sourceElem = get_element_type(sourceTypeId)) != InvalidOid)
3258
0
      {
3259
0
        CoercionPathType elempathtype;
3260
0
        Oid     elemfuncid;
3261
3262
0
        elempathtype = find_coercion_pathway(targetElem,
3263
0
                           sourceElem,
3264
0
                           ccontext,
3265
0
                           &elemfuncid);
3266
0
        if (elempathtype != COERCION_PATH_NONE)
3267
0
        {
3268
0
          result = COERCION_PATH_ARRAYCOERCE;
3269
0
        }
3270
0
      }
3271
0
    }
3272
3273
    /*
3274
     * If we still haven't found a possibility, consider automatic casting
3275
     * using I/O functions.  We allow assignment casts to string types and
3276
     * explicit casts from string types to be handled this way. (The
3277
     * CoerceViaIO mechanism is a lot more general than that, but this is
3278
     * all we want to allow in the absence of a pg_cast entry.) It would
3279
     * probably be better to insist on explicit casts in both directions,
3280
     * but this is a compromise to preserve something of the pre-8.3
3281
     * behavior that many types had implicit (yipes!) casts to text.
3282
     */
3283
0
    if (result == COERCION_PATH_NONE)
3284
0
    {
3285
0
      if (ccontext >= COERCION_ASSIGNMENT &&
3286
0
        TypeCategory(targetTypeId) == TYPCATEGORY_STRING)
3287
0
        result = COERCION_PATH_COERCEVIAIO;
3288
0
      else if (ccontext >= COERCION_EXPLICIT &&
3289
0
           TypeCategory(sourceTypeId) == TYPCATEGORY_STRING)
3290
0
        result = COERCION_PATH_COERCEVIAIO;
3291
0
    }
3292
0
  }
3293
3294
  /*
3295
   * When parsing PL/pgSQL assignments, allow an I/O cast to be used
3296
   * whenever no normal coercion is available.
3297
   */
3298
0
  if (result == COERCION_PATH_NONE &&
3299
0
    ccontext == COERCION_PLPGSQL)
3300
0
    result = COERCION_PATH_COERCEVIAIO;
3301
3302
0
  return result;
3303
0
}
3304
3305
3306
/*
3307
 * find_typmod_coercion_function -- does the given type need length coercion?
3308
 *
3309
 * If the target type possesses a pg_cast function from itself to itself,
3310
 * it must need length coercion.
3311
 *
3312
 * "bpchar" (ie, char(N)) and "numeric" are examples of such types.
3313
 *
3314
 * If the given type is a varlena array type, we do not look for a coercion
3315
 * function associated directly with the array type, but instead look for
3316
 * one associated with the element type.  An ArrayCoerceExpr node must be
3317
 * used to apply such a function.  (Note: currently, it's pointless to
3318
 * return the funcid in this case, because it'll just get looked up again
3319
 * in the recursive construction of the ArrayCoerceExpr's elemexpr.)
3320
 *
3321
 * We use the same result enum as find_coercion_pathway, but the only possible
3322
 * result codes are:
3323
 *  COERCION_PATH_NONE: no length coercion needed
3324
 *  COERCION_PATH_FUNC: apply the function returned in *funcid
3325
 *  COERCION_PATH_ARRAYCOERCE: apply the function using ArrayCoerceExpr
3326
 */
3327
CoercionPathType
3328
find_typmod_coercion_function(Oid typeId,
3329
                Oid *funcid)
3330
0
{
3331
0
  CoercionPathType result;
3332
0
  Type    targetType;
3333
0
  Form_pg_type typeForm;
3334
0
  HeapTuple tuple;
3335
3336
0
  *funcid = InvalidOid;
3337
0
  result = COERCION_PATH_FUNC;
3338
3339
0
  targetType = typeidType(typeId);
3340
0
  typeForm = (Form_pg_type) GETSTRUCT(targetType);
3341
3342
  /* Check for a "true" array type */
3343
0
  if (IsTrueArrayType(typeForm))
3344
0
  {
3345
    /* Yes, switch our attention to the element type */
3346
0
    typeId = typeForm->typelem;
3347
0
    result = COERCION_PATH_ARRAYCOERCE;
3348
0
  }
3349
0
  ReleaseSysCache(targetType);
3350
3351
  /* Look in pg_cast */
3352
0
  tuple = SearchSysCache2(CASTSOURCETARGET,
3353
0
              ObjectIdGetDatum(typeId),
3354
0
              ObjectIdGetDatum(typeId));
3355
3356
0
  if (HeapTupleIsValid(tuple))
3357
0
  {
3358
0
    Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
3359
3360
0
    *funcid = castForm->castfunc;
3361
0
    ReleaseSysCache(tuple);
3362
0
  }
3363
3364
0
  if (!OidIsValid(*funcid))
3365
0
    result = COERCION_PATH_NONE;
3366
3367
0
  return result;
3368
0
}
3369
3370
/*
3371
 * is_complex_array
3372
 *    Is this type an array of composite?
3373
 *
3374
 * Note: this will not return true for record[]; check for RECORDARRAYOID
3375
 * separately if needed.
3376
 */
3377
static bool
3378
is_complex_array(Oid typid)
3379
0
{
3380
0
  Oid     elemtype = get_element_type(typid);
3381
3382
0
  return (OidIsValid(elemtype) && ISCOMPLEX(elemtype));
3383
0
}
3384
3385
3386
/*
3387
 * Check whether reltypeId is the row type of a typed table of type
3388
 * reloftypeId, or is a domain over such a row type.  (This is conceptually
3389
 * similar to the subtype relationship checked by typeInheritsFrom().)
3390
 */
3391
static bool
3392
typeIsOfTypedTable(Oid reltypeId, Oid reloftypeId)
3393
0
{
3394
0
  Oid     relid = typeOrDomainTypeRelid(reltypeId);
3395
0
  bool    result = false;
3396
3397
0
  if (relid)
3398
0
  {
3399
0
    HeapTuple tp;
3400
0
    Form_pg_class reltup;
3401
3402
0
    tp = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
3403
0
    if (!HeapTupleIsValid(tp))
3404
0
      elog(ERROR, "cache lookup failed for relation %u", relid);
3405
3406
0
    reltup = (Form_pg_class) GETSTRUCT(tp);
3407
0
    if (reltup->reloftype == reloftypeId)
3408
0
      result = true;
3409
3410
0
    ReleaseSysCache(tp);
3411
0
  }
3412
3413
0
  return result;
3414
0
}