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