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