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