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