1 /*------------------------------------------------------------------------- 2 * 3 * parse_func.c 4 * handle function calls in parser 5 * 6 * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group 7 * Portions Copyright (c) 1994, Regents of the University of California 8 * 9 * 10 * IDENTIFICATION 11 * src/backend/parser/parse_func.c 12 * 13 *------------------------------------------------------------------------- 14 */ 15 #include "postgres.h" 16 17 #include "access/htup_details.h" 18 #include "catalog/pg_aggregate.h" 19 #include "catalog/pg_proc.h" 20 #include "catalog/pg_type.h" 21 #include "funcapi.h" 22 #include "lib/stringinfo.h" 23 #include "nodes/makefuncs.h" 24 #include "nodes/nodeFuncs.h" 25 #include "parser/parse_agg.h" 26 #include "parser/parse_clause.h" 27 #include "parser/parse_coerce.h" 28 #include "parser/parse_expr.h" 29 #include "parser/parse_func.h" 30 #include "parser/parse_relation.h" 31 #include "parser/parse_target.h" 32 #include "parser/parse_type.h" 33 #include "utils/builtins.h" 34 #include "utils/lsyscache.h" 35 #include "utils/syscache.h" 36 37 38 /* Possible error codes from LookupFuncNameInternal */ 39 typedef enum 40 { hash2_key(const uchar * rec,uint * length,my_bool not_used)41 FUNCLOOKUP_NOSUCHFUNC, 42 FUNCLOOKUP_AMBIGUOUS 43 } FuncLookupError; 44 45 static void unify_hypothetical_args(ParseState *pstate, 46 List *fargs, int numAggregatedArgs, 47 Oid *actual_arg_types, Oid *declared_arg_types); 48 static Oid FuncNameAsType(List *funcname); 49 static Node *ParseComplexProjection(ParseState *pstate, const char *funcname, main(int argc,char * argv[])50 Node *first_arg, int location); 51 static Oid LookupFuncNameInternal(List *funcname, int nargs, 52 const Oid *argtypes, 53 bool missing_ok, FuncLookupError *lookupError); 54 55 56 /* 57 * Parse a function call 58 * 59 * For historical reasons, Postgres tries to treat the notations tab.col do_test()60 * and col(tab) as equivalent: if a single-argument function call has an 61 * argument of complex type and the (unqualified) function name matches 62 * any attribute of the type, we can interpret it as a column projection. 63 * Conversely a function of a single complex-type argument can be written 64 * like a column reference, allowing functions to act like computed columns. 65 * 66 * If both interpretations are possible, we prefer the one matching the 67 * syntactic form, but otherwise the form does not matter. 68 * 69 * Hence, both cases come through here. If fn is null, we're dealing with 70 * column syntax not function syntax. In the function-syntax case, 71 * the FuncCall struct is needed to carry various decoration that applies 72 * to aggregate and window functions. 73 * 74 * Also, when fn is null, we return NULL on failure rather than 75 * reporting a no-such-function error. 76 * 77 * The argument expressions (in fargs) must have been transformed 78 * already. However, nothing in *fn has been transformed. 79 * 80 * last_srf should be a copy of pstate->p_last_srf from just before we 81 * started transforming fargs. If the caller knows that fargs couldn't 82 * contain any SRF calls, last_srf can just be pstate->p_last_srf. 83 * 84 * proc_call is true if we are considering a CALL statement, so that the 85 * name must resolve to a procedure name, not anything else. 86 */ 87 Node * 88 ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, 89 Node *last_srf, FuncCall *fn, bool proc_call, int location) 90 { 91 bool is_column = (fn == NULL); 92 List *agg_order = (fn ? fn->agg_order : NIL); 93 Expr *agg_filter = NULL; 94 bool agg_within_group = (fn ? fn->agg_within_group : false); 95 bool agg_star = (fn ? fn->agg_star : false); 96 bool agg_distinct = (fn ? fn->agg_distinct : false); 97 bool func_variadic = (fn ? fn->func_variadic : false); 98 WindowDef *over = (fn ? fn->over : NULL); 99 bool could_be_projection; 100 Oid rettype; 101 Oid funcid; 102 ListCell *l; 103 Node *first_arg = NULL; 104 int nargs; 105 int nargsplusdefs; 106 Oid actual_arg_types[FUNC_MAX_ARGS]; 107 Oid *declared_arg_types; 108 List *argnames; 109 List *argdefaults; 110 Node *retval; 111 bool retset; 112 int nvargs; 113 Oid vatype; 114 FuncDetailCode fdresult; 115 char aggkind = 0; 116 ParseCallbackState pcbstate; 117 118 /* 119 * If there's an aggregate filter, transform it using transformWhereClause 120 */ 121 if (fn && fn->agg_filter != NULL) 122 agg_filter = (Expr *) transformWhereClause(pstate, fn->agg_filter, 123 EXPR_KIND_FILTER, 124 "FILTER"); 125 126 /* 127 * Most of the rest of the parser just assumes that functions do not have 128 * more than FUNC_MAX_ARGS parameters. We have to test here to protect 129 * against array overruns, etc. Of course, this may not be a function, 130 * but the test doesn't hurt. 131 */ 132 if (list_length(fargs) > FUNC_MAX_ARGS) 133 ereport(ERROR, 134 (errcode(ERRCODE_TOO_MANY_ARGUMENTS), 135 errmsg_plural("cannot pass more than %d argument to a function", 136 "cannot pass more than %d arguments to a function", 137 FUNC_MAX_ARGS, 138 FUNC_MAX_ARGS), 139 parser_errposition(pstate, location))); 140 141 /* 142 * Extract arg type info in preparation for function lookup. 143 * 144 * If any arguments are Param markers of type VOID, we discard them from 145 * the parameter list. This is a hack to allow the JDBC driver to not have 146 * to distinguish "input" and "output" parameter symbols while parsing 147 * function-call constructs. Don't do this if dealing with column syntax, 148 * nor if we had WITHIN GROUP (because in that case it's critical to keep 149 * the argument count unchanged). 150 */ 151 nargs = 0; 152 foreach(l, fargs) 153 { 154 Node *arg = lfirst(l); 155 Oid argtype = exprType(arg); 156 157 if (argtype == VOIDOID && IsA(arg, Param) && 158 !is_column && !agg_within_group) 159 { 160 fargs = foreach_delete_current(fargs, l); 161 continue; 162 } 163 164 actual_arg_types[nargs++] = argtype; 165 } 166 167 /* 168 * Check for named arguments; if there are any, build a list of names. 169 * 170 * We allow mixed notation (some named and some not), but only with all 171 * the named parameters after all the unnamed ones. So the name list 172 * corresponds to the last N actual parameters and we don't need any extra 173 * bookkeeping to match things up. 174 */ 175 argnames = NIL; 176 foreach(l, fargs) 177 { 178 Node *arg = lfirst(l); 179 180 if (IsA(arg, NamedArgExpr)) 181 { 182 NamedArgExpr *na = (NamedArgExpr *) arg; 183 ListCell *lc; 184 185 /* Reject duplicate arg names */ 186 foreach(lc, argnames) 187 { 188 if (strcmp(na->name, (char *) lfirst(lc)) == 0) 189 ereport(ERROR, 190 (errcode(ERRCODE_SYNTAX_ERROR), 191 errmsg("argument name \"%s\" used more than once", 192 na->name), 193 parser_errposition(pstate, na->location))); 194 } 195 argnames = lappend(argnames, na->name); 196 } 197 else 198 { 199 if (argnames != NIL) 200 ereport(ERROR, 201 (errcode(ERRCODE_SYNTAX_ERROR), 202 errmsg("positional argument cannot follow named argument"), 203 parser_errposition(pstate, exprLocation(arg)))); 204 } 205 } 206 207 if (fargs) 208 { 209 first_arg = linitial(fargs); 210 Assert(first_arg != NULL); 211 } 212 213 /* 214 * Decide whether it's legitimate to consider the construct to be a column 215 * projection. For that, there has to be a single argument of complex 216 * type, the function name must not be qualified, and there cannot be any 217 * syntactic decoration that'd require it to be a function (such as 218 * aggregate or variadic decoration, or named arguments). 219 */ 220 could_be_projection = (nargs == 1 && !proc_call && 221 agg_order == NIL && agg_filter == NULL && 222 !agg_star && !agg_distinct && over == NULL && 223 !func_variadic && argnames == NIL && 224 list_length(funcname) == 1 && 225 (actual_arg_types[0] == RECORDOID || 226 ISCOMPLEX(actual_arg_types[0]))); 227 228 /* 229 * If it's column syntax, check for column projection case first. 230 */ 231 if (could_be_projection && is_column) 232 { 233 retval = ParseComplexProjection(pstate, 234 strVal(linitial(funcname)), 235 first_arg, 236 location); 237 if (retval) 238 return retval; 239 240 /* 241 * If ParseComplexProjection doesn't recognize it as a projection, 242 * just press on. 243 */ 244 } 245 246 /* 247 * func_get_detail looks up the function in the catalogs, does 248 * disambiguation for polymorphic functions, handles inheritance, and 249 * returns the funcid and type and set or singleton status of the 250 * function's return value. It also returns the true argument types to 251 * the function. 252 * 253 * Note: for a named-notation or variadic function call, the reported 254 * "true" types aren't really what is in pg_proc: the types are reordered 255 * to match the given argument order of named arguments, and a variadic 256 * argument is replaced by a suitable number of copies of its element 257 * type. We'll fix up the variadic case below. We may also have to deal 258 * with default arguments. 259 */ 260 261 setup_parser_errposition_callback(&pcbstate, pstate, location); 262 263 fdresult = func_get_detail(funcname, fargs, argnames, nargs, 264 actual_arg_types, 265 !func_variadic, true, 266 &funcid, &rettype, &retset, 267 &nvargs, &vatype, 268 &declared_arg_types, &argdefaults); 269 270 cancel_parser_errposition_callback(&pcbstate); 271 272 /* 273 * Check for various wrong-kind-of-routine cases. 274 */ 275 276 /* If this is a CALL, reject things that aren't procedures */ 277 if (proc_call && 278 (fdresult == FUNCDETAIL_NORMAL || 279 fdresult == FUNCDETAIL_AGGREGATE || 280 fdresult == FUNCDETAIL_WINDOWFUNC || 281 fdresult == FUNCDETAIL_COERCION)) 282 ereport(ERROR, 283 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 284 errmsg("%s is not a procedure", 285 func_signature_string(funcname, nargs, 286 argnames, 287 actual_arg_types)), 288 errhint("To call a function, use SELECT."), 289 parser_errposition(pstate, location))); 290 /* Conversely, if not a CALL, reject procedures */ 291 if (fdresult == FUNCDETAIL_PROCEDURE && !proc_call) 292 ereport(ERROR, 293 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 294 errmsg("%s is a procedure", 295 func_signature_string(funcname, nargs, 296 argnames, 297 actual_arg_types)), 298 errhint("To call a procedure, use CALL."), 299 parser_errposition(pstate, location))); 300 301 if (fdresult == FUNCDETAIL_NORMAL || 302 fdresult == FUNCDETAIL_PROCEDURE || 303 fdresult == FUNCDETAIL_COERCION) 304 { 305 /* 306 * In these cases, complain if there was anything indicating it must 307 * be an aggregate or window function. 308 */ 309 if (agg_star) 310 ereport(ERROR, 311 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 312 errmsg("%s(*) specified, but %s is not an aggregate function", 313 NameListToString(funcname), 314 NameListToString(funcname)), 315 parser_errposition(pstate, location))); 316 if (agg_distinct) 317 ereport(ERROR, 318 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 319 errmsg("DISTINCT specified, but %s is not an aggregate function", 320 NameListToString(funcname)), 321 parser_errposition(pstate, location))); 322 if (agg_within_group) 323 ereport(ERROR, 324 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 325 errmsg("WITHIN GROUP specified, but %s is not an aggregate function", 326 NameListToString(funcname)), 327 parser_errposition(pstate, location))); 328 if (agg_order != NIL) 329 ereport(ERROR, 330 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 331 errmsg("ORDER BY specified, but %s is not an aggregate function", 332 NameListToString(funcname)), 333 parser_errposition(pstate, location))); 334 if (agg_filter) 335 ereport(ERROR, 336 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 337 errmsg("FILTER specified, but %s is not an aggregate function", 338 NameListToString(funcname)), 339 parser_errposition(pstate, location))); 340 if (over) 341 ereport(ERROR, 342 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 343 errmsg("OVER specified, but %s is not a window function nor an aggregate function", 344 NameListToString(funcname)), 345 parser_errposition(pstate, location))); 346 } 347 348 /* 349 * So far so good, so do some fdresult-type-specific processing. 350 */ 351 if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE) 352 { 353 /* Nothing special to do for these cases. */ 354 } 355 else if (fdresult == FUNCDETAIL_AGGREGATE) 356 { 357 /* 358 * It's an aggregate; fetch needed info from the pg_aggregate entry. 359 */ 360 HeapTuple tup; 361 Form_pg_aggregate classForm; 362 int catDirectArgs; 363 364 tup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(funcid)); 365 if (!HeapTupleIsValid(tup)) /* should not happen */ 366 elog(ERROR, "cache lookup failed for aggregate %u", funcid); 367 classForm = (Form_pg_aggregate) GETSTRUCT(tup); 368 aggkind = classForm->aggkind; 369 catDirectArgs = classForm->aggnumdirectargs; 370 ReleaseSysCache(tup); 371 372 /* Now check various disallowed cases. */ 373 if (AGGKIND_IS_ORDERED_SET(aggkind)) 374 { 375 int numAggregatedArgs; 376 int numDirectArgs; 377 378 if (!agg_within_group) 379 ereport(ERROR, 380 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 381 errmsg("WITHIN GROUP is required for ordered-set aggregate %s", 382 NameListToString(funcname)), 383 parser_errposition(pstate, location))); 384 if (over) 385 ereport(ERROR, 386 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 387 errmsg("OVER is not supported for ordered-set aggregate %s", 388 NameListToString(funcname)), 389 parser_errposition(pstate, location))); 390 /* gram.y rejects DISTINCT + WITHIN GROUP */ 391 Assert(!agg_distinct); 392 /* gram.y rejects VARIADIC + WITHIN GROUP */ 393 Assert(!func_variadic); 394 395 /* 396 * Since func_get_detail was working with an undifferentiated list 397 * of arguments, it might have selected an aggregate that doesn't 398 * really match because it requires a different division of direct 399 * and aggregated arguments. Check that the number of direct 400 * arguments is actually OK; if not, throw an "undefined function" 401 * error, similarly to the case where a misplaced ORDER BY is used 402 * in a regular aggregate call. 403 */ 404 numAggregatedArgs = list_length(agg_order); 405 numDirectArgs = nargs - numAggregatedArgs; 406 Assert(numDirectArgs >= 0); 407 408 if (!OidIsValid(vatype)) 409 { 410 /* Test is simple if aggregate isn't variadic */ 411 if (numDirectArgs != catDirectArgs) 412 ereport(ERROR, 413 (errcode(ERRCODE_UNDEFINED_FUNCTION), 414 errmsg("function %s does not exist", 415 func_signature_string(funcname, nargs, 416 argnames, 417 actual_arg_types)), 418 errhint("There is an ordered-set aggregate %s, but it requires %d direct arguments, not %d.", 419 NameListToString(funcname), 420 catDirectArgs, numDirectArgs), 421 parser_errposition(pstate, location))); 422 } 423 else 424 { 425 /* 426 * If it's variadic, we have two cases depending on whether 427 * the agg was "... ORDER BY VARIADIC" or "..., VARIADIC ORDER 428 * BY VARIADIC". It's the latter if catDirectArgs equals 429 * pronargs; to save a catalog lookup, we reverse-engineer 430 * pronargs from the info we got from func_get_detail. 431 */ 432 int pronargs; 433 434 pronargs = nargs; 435 if (nvargs > 1) 436 pronargs -= nvargs - 1; 437 if (catDirectArgs < pronargs) 438 { 439 /* VARIADIC isn't part of direct args, so still easy */ 440 if (numDirectArgs != catDirectArgs) 441 ereport(ERROR, 442 (errcode(ERRCODE_UNDEFINED_FUNCTION), 443 errmsg("function %s does not exist", 444 func_signature_string(funcname, nargs, 445 argnames, 446 actual_arg_types)), 447 errhint("There is an ordered-set aggregate %s, but it requires %d direct arguments, not %d.", 448 NameListToString(funcname), 449 catDirectArgs, numDirectArgs), 450 parser_errposition(pstate, location))); 451 } 452 else 453 { 454 /* 455 * Both direct and aggregated args were declared variadic. 456 * For a standard ordered-set aggregate, it's okay as long 457 * as there aren't too few direct args. For a 458 * hypothetical-set aggregate, we assume that the 459 * hypothetical arguments are those that matched the 460 * variadic parameter; there must be just as many of them 461 * as there are aggregated arguments. 462 */ 463 if (aggkind == AGGKIND_HYPOTHETICAL) 464 { 465 if (nvargs != 2 * numAggregatedArgs) 466 ereport(ERROR, 467 (errcode(ERRCODE_UNDEFINED_FUNCTION), 468 errmsg("function %s does not exist", 469 func_signature_string(funcname, nargs, 470 argnames, 471 actual_arg_types)), 472 errhint("To use the hypothetical-set aggregate %s, the number of hypothetical direct arguments (here %d) must match the number of ordering columns (here %d).", 473 NameListToString(funcname), 474 nvargs - numAggregatedArgs, numAggregatedArgs), 475 parser_errposition(pstate, location))); 476 } 477 else 478 { 479 if (nvargs <= numAggregatedArgs) 480 ereport(ERROR, 481 (errcode(ERRCODE_UNDEFINED_FUNCTION), 482 errmsg("function %s does not exist", 483 func_signature_string(funcname, nargs, 484 argnames, 485 actual_arg_types)), 486 errhint("There is an ordered-set aggregate %s, but it requires at least %d direct arguments.", 487 NameListToString(funcname), 488 catDirectArgs), 489 parser_errposition(pstate, location))); 490 } 491 } 492 } 493 494 /* Check type matching of hypothetical arguments */ 495 if (aggkind == AGGKIND_HYPOTHETICAL) 496 unify_hypothetical_args(pstate, fargs, numAggregatedArgs, 497 actual_arg_types, declared_arg_types); 498 } 499 else 500 { 501 /* Normal aggregate, so it can't have WITHIN GROUP */ 502 if (agg_within_group) 503 ereport(ERROR, 504 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 505 errmsg("%s is not an ordered-set aggregate, so it cannot have WITHIN GROUP", 506 NameListToString(funcname)), 507 parser_errposition(pstate, location))); 508 } 509 } 510 else if (fdresult == FUNCDETAIL_WINDOWFUNC) 511 { 512 /* 513 * True window functions must be called with a window definition. 514 */ 515 if (!over) 516 ereport(ERROR, 517 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 518 errmsg("window function %s requires an OVER clause", 519 NameListToString(funcname)), 520 parser_errposition(pstate, location))); 521 /* And, per spec, WITHIN GROUP isn't allowed */ 522 if (agg_within_group) 523 ereport(ERROR, 524 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 525 errmsg("window function %s cannot have WITHIN GROUP", 526 NameListToString(funcname)), 527 parser_errposition(pstate, location))); 528 } 529 else if (fdresult == FUNCDETAIL_COERCION) 530 { 531 /* 532 * We interpreted it as a type coercion. coerce_type can handle these 533 * cases, so why duplicate code... 534 */ 535 return coerce_type(pstate, linitial(fargs), 536 actual_arg_types[0], rettype, -1, 537 COERCION_EXPLICIT, COERCE_EXPLICIT_CALL, location); 538 } 539 else if (fdresult == FUNCDETAIL_MULTIPLE) 540 { 541 /* 542 * We found multiple possible functional matches. If we are dealing 543 * with attribute notation, return failure, letting the caller report 544 * "no such column" (we already determined there wasn't one). If 545 * dealing with function notation, report "ambiguous function", 546 * regardless of whether there's also a column by this name. 547 */ 548 if (is_column) 549 return NULL; 550 551 if (proc_call) 552 ereport(ERROR, 553 (errcode(ERRCODE_AMBIGUOUS_FUNCTION), 554 errmsg("procedure %s is not unique", 555 func_signature_string(funcname, nargs, argnames, 556 actual_arg_types)), 557 errhint("Could not choose a best candidate procedure. " 558 "You might need to add explicit type casts."), 559 parser_errposition(pstate, location))); 560 else 561 ereport(ERROR, 562 (errcode(ERRCODE_AMBIGUOUS_FUNCTION), 563 errmsg("function %s is not unique", 564 func_signature_string(funcname, nargs, argnames, 565 actual_arg_types)), 566 errhint("Could not choose a best candidate function. " 567 "You might need to add explicit type casts."), 568 parser_errposition(pstate, location))); 569 } 570 else 571 { 572 /* 573 * Not found as a function. If we are dealing with attribute 574 * notation, return failure, letting the caller report "no such 575 * column" (we already determined there wasn't one). 576 */ 577 if (is_column) 578 return NULL; 579 580 /* 581 * Check for column projection interpretation, since we didn't before. 582 */ 583 if (could_be_projection) 584 { 585 retval = ParseComplexProjection(pstate, 586 strVal(linitial(funcname)), 587 first_arg, 588 location); 589 if (retval) 590 return retval; 591 } 592 593 /* 594 * No function, and no column either. Since we're dealing with 595 * function notation, report "function does not exist". 596 */ 597 if (list_length(agg_order) > 1 && !agg_within_group) 598 { 599 /* It's agg(x, ORDER BY y,z) ... perhaps misplaced ORDER BY */ 600 ereport(ERROR, 601 (errcode(ERRCODE_UNDEFINED_FUNCTION), 602 errmsg("function %s does not exist", 603 func_signature_string(funcname, nargs, argnames, 604 actual_arg_types)), 605 errhint("No aggregate function matches the given name and argument types. " 606 "Perhaps you misplaced ORDER BY; ORDER BY must appear " 607 "after all regular arguments of the aggregate."), 608 parser_errposition(pstate, location))); 609 } 610 else if (proc_call) 611 ereport(ERROR, 612 (errcode(ERRCODE_UNDEFINED_FUNCTION), 613 errmsg("procedure %s does not exist", 614 func_signature_string(funcname, nargs, argnames, 615 actual_arg_types)), 616 errhint("No procedure matches the given name and argument types. " 617 "You might need to add explicit type casts."), 618 parser_errposition(pstate, location))); 619 else 620 ereport(ERROR, 621 (errcode(ERRCODE_UNDEFINED_FUNCTION), 622 errmsg("function %s does not exist", 623 func_signature_string(funcname, nargs, argnames, 624 actual_arg_types)), 625 errhint("No function matches the given name and argument types. " 626 "You might need to add explicit type casts."), 627 parser_errposition(pstate, location))); 628 } 629 630 /* 631 * If there are default arguments, we have to include their types in 632 * actual_arg_types for the purpose of checking generic type consistency. 633 * However, we do NOT put them into the generated parse node, because 634 * their actual values might change before the query gets run. The 635 * planner has to insert the up-to-date values at plan time. 636 */ 637 nargsplusdefs = nargs; 638 foreach(l, argdefaults) 639 { 640 Node *expr = (Node *) lfirst(l); 641 642 /* probably shouldn't happen ... */ 643 if (nargsplusdefs >= FUNC_MAX_ARGS) 644 ereport(ERROR, 645 (errcode(ERRCODE_TOO_MANY_ARGUMENTS), 646 errmsg_plural("cannot pass more than %d argument to a function", 647 "cannot pass more than %d arguments to a function", 648 FUNC_MAX_ARGS, 649 FUNC_MAX_ARGS), 650 parser_errposition(pstate, location))); 651 652 actual_arg_types[nargsplusdefs++] = exprType(expr); 653 } 654 655 /* 656 * enforce consistency with polymorphic argument and return types, 657 * possibly adjusting return type or declared_arg_types (which will be 658 * used as the cast destination by make_fn_arguments) 659 */ 660 rettype = enforce_generic_type_consistency(actual_arg_types, 661 declared_arg_types, 662 nargsplusdefs, 663 rettype, 664 false); 665 666 /* perform the necessary typecasting of arguments */ 667 make_fn_arguments(pstate, fargs, actual_arg_types, declared_arg_types); 668 669 /* 670 * If the function isn't actually variadic, forget any VARIADIC decoration 671 * on the call. (Perhaps we should throw an error instead, but 672 * historically we've allowed people to write that.) 673 */ 674 if (!OidIsValid(vatype)) 675 { 676 Assert(nvargs == 0); 677 func_variadic = false; 678 } 679 680 /* 681 * If it's a variadic function call, transform the last nvargs arguments 682 * into an array --- unless it's an "any" variadic. 683 */ 684 if (nvargs > 0 && vatype != ANYOID) 685 { 686 ArrayExpr *newa = makeNode(ArrayExpr); 687 int non_var_args = nargs - nvargs; 688 List *vargs; 689 690 Assert(non_var_args >= 0); 691 vargs = list_copy_tail(fargs, non_var_args); 692 fargs = list_truncate(fargs, non_var_args); 693 694 newa->elements = vargs; 695 /* assume all the variadic arguments were coerced to the same type */ 696 newa->element_typeid = exprType((Node *) linitial(vargs)); 697 newa->array_typeid = get_array_type(newa->element_typeid); 698 if (!OidIsValid(newa->array_typeid)) 699 ereport(ERROR, 700 (errcode(ERRCODE_UNDEFINED_OBJECT), 701 errmsg("could not find array type for data type %s", 702 format_type_be(newa->element_typeid)), 703 parser_errposition(pstate, exprLocation((Node *) vargs)))); 704 /* array_collid will be set by parse_collate.c */ 705 newa->multidims = false; 706 newa->location = exprLocation((Node *) vargs); 707 708 fargs = lappend(fargs, newa); 709 710 /* We could not have had VARIADIC marking before ... */ 711 Assert(!func_variadic); 712 /* ... but now, it's a VARIADIC call */ 713 func_variadic = true; 714 } 715 716 /* 717 * If an "any" variadic is called with explicit VARIADIC marking, insist 718 * that the variadic parameter be of some array type. 719 */ 720 if (nargs > 0 && vatype == ANYOID && func_variadic) 721 { 722 Oid va_arr_typid = actual_arg_types[nargs - 1]; 723 724 if (!OidIsValid(get_base_element_type(va_arr_typid))) 725 ereport(ERROR, 726 (errcode(ERRCODE_DATATYPE_MISMATCH), 727 errmsg("VARIADIC argument must be an array"), 728 parser_errposition(pstate, 729 exprLocation((Node *) llast(fargs))))); 730 } 731 732 /* if it returns a set, check that's OK */ 733 if (retset) 734 check_srf_call_placement(pstate, last_srf, location); 735 736 /* build the appropriate output structure */ 737 if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE) 738 { 739 FuncExpr *funcexpr = makeNode(FuncExpr); 740 741 funcexpr->funcid = funcid; 742 funcexpr->funcresulttype = rettype; 743 funcexpr->funcretset = retset; 744 funcexpr->funcvariadic = func_variadic; 745 funcexpr->funcformat = COERCE_EXPLICIT_CALL; 746 /* funccollid and inputcollid will be set by parse_collate.c */ 747 funcexpr->args = fargs; 748 funcexpr->location = location; 749 750 retval = (Node *) funcexpr; 751 } 752 else if (fdresult == FUNCDETAIL_AGGREGATE && !over) 753 { 754 /* aggregate function */ 755 Aggref *aggref = makeNode(Aggref); 756 757 aggref->aggfnoid = funcid; 758 aggref->aggtype = rettype; 759 /* aggcollid and inputcollid will be set by parse_collate.c */ 760 aggref->aggtranstype = InvalidOid; /* will be set by planner */ 761 /* aggargtypes will be set by transformAggregateCall */ 762 /* aggdirectargs and args will be set by transformAggregateCall */ 763 /* aggorder and aggdistinct will be set by transformAggregateCall */ 764 aggref->aggfilter = agg_filter; 765 aggref->aggstar = agg_star; 766 aggref->aggvariadic = func_variadic; 767 aggref->aggkind = aggkind; 768 /* agglevelsup will be set by transformAggregateCall */ 769 aggref->aggsplit = AGGSPLIT_SIMPLE; /* planner might change this */ 770 aggref->location = location; 771 772 /* 773 * Reject attempt to call a parameterless aggregate without (*) 774 * syntax. This is mere pedantry but some folks insisted ... 775 */ 776 if (fargs == NIL && !agg_star && !agg_within_group) 777 ereport(ERROR, 778 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 779 errmsg("%s(*) must be used to call a parameterless aggregate function", 780 NameListToString(funcname)), 781 parser_errposition(pstate, location))); 782 783 if (retset) 784 ereport(ERROR, 785 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), 786 errmsg("aggregates cannot return sets"), 787 parser_errposition(pstate, location))); 788 789 /* 790 * We might want to support named arguments later, but disallow it for 791 * now. We'd need to figure out the parsed representation (should the 792 * NamedArgExprs go above or below the TargetEntry nodes?) and then 793 * teach the planner to reorder the list properly. Or maybe we could 794 * make transformAggregateCall do that? However, if you'd also like 795 * to allow default arguments for aggregates, we'd need to do it in 796 * planning to avoid semantic problems. 797 */ 798 if (argnames != NIL) 799 ereport(ERROR, 800 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 801 errmsg("aggregates cannot use named arguments"), 802 parser_errposition(pstate, location))); 803 804 /* parse_agg.c does additional aggregate-specific processing */ 805 transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct); 806 807 retval = (Node *) aggref; 808 } 809 else 810 { 811 /* window function */ 812 WindowFunc *wfunc = makeNode(WindowFunc); 813 814 Assert(over); /* lack of this was checked above */ 815 Assert(!agg_within_group); /* also checked above */ 816 817 wfunc->winfnoid = funcid; 818 wfunc->wintype = rettype; 819 /* wincollid and inputcollid will be set by parse_collate.c */ 820 wfunc->args = fargs; 821 /* winref will be set by transformWindowFuncCall */ 822 wfunc->winstar = agg_star; 823 wfunc->winagg = (fdresult == FUNCDETAIL_AGGREGATE); 824 wfunc->aggfilter = agg_filter; 825 wfunc->location = location; 826 827 /* 828 * agg_star is allowed for aggregate functions but distinct isn't 829 */ 830 if (agg_distinct) 831 ereport(ERROR, 832 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 833 errmsg("DISTINCT is not implemented for window functions"), 834 parser_errposition(pstate, location))); 835 836 /* 837 * Reject attempt to call a parameterless aggregate without (*) 838 * syntax. This is mere pedantry but some folks insisted ... 839 */ 840 if (wfunc->winagg && fargs == NIL && !agg_star) 841 ereport(ERROR, 842 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 843 errmsg("%s(*) must be used to call a parameterless aggregate function", 844 NameListToString(funcname)), 845 parser_errposition(pstate, location))); 846 847 /* 848 * ordered aggs not allowed in windows yet 849 */ 850 if (agg_order != NIL) 851 ereport(ERROR, 852 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 853 errmsg("aggregate ORDER BY is not implemented for window functions"), 854 parser_errposition(pstate, location))); 855 856 /* 857 * FILTER is not yet supported with true window functions 858 */ 859 if (!wfunc->winagg && agg_filter) 860 ereport(ERROR, 861 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 862 errmsg("FILTER is not implemented for non-aggregate window functions"), 863 parser_errposition(pstate, location))); 864 865 /* 866 * Window functions can't either take or return sets 867 */ 868 if (pstate->p_last_srf != last_srf) 869 ereport(ERROR, 870 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 871 errmsg("window function calls cannot contain set-returning function calls"), 872 errhint("You might be able to move the set-returning function into a LATERAL FROM item."), 873 parser_errposition(pstate, 874 exprLocation(pstate->p_last_srf)))); 875 876 if (retset) 877 ereport(ERROR, 878 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), 879 errmsg("window functions cannot return sets"), 880 parser_errposition(pstate, location))); 881 882 /* parse_agg.c does additional window-func-specific processing */ 883 transformWindowFuncCall(pstate, wfunc, over); 884 885 retval = (Node *) wfunc; 886 } 887 888 /* if it returns a set, remember it for error checks at higher levels */ 889 if (retset) 890 pstate->p_last_srf = retval; 891 892 return retval; 893 } 894 895 896 /* func_match_argtypes() 897 * 898 * Given a list of candidate functions (having the right name and number 899 * of arguments) and an array of input datatype OIDs, produce a shortlist of 900 * those candidates that actually accept the input datatypes (either exactly 901 * or by coercion), and return the number of such candidates. 902 * 903 * Note that can_coerce_type will assume that UNKNOWN inputs are coercible to 904 * anything, so candidates will not be eliminated on that basis. 905 * 906 * NB: okay to modify input list structure, as long as we find at least 907 * one match. If no match at all, the list must remain unmodified. 908 */ 909 int 910 func_match_argtypes(int nargs, 911 Oid *input_typeids, 912 FuncCandidateList raw_candidates, 913 FuncCandidateList *candidates) /* return value */ 914 { 915 FuncCandidateList current_candidate; 916 FuncCandidateList next_candidate; 917 int ncandidates = 0; 918 919 *candidates = NULL; 920 921 for (current_candidate = raw_candidates; 922 current_candidate != NULL; 923 current_candidate = next_candidate) 924 { 925 next_candidate = current_candidate->next; 926 if (can_coerce_type(nargs, input_typeids, current_candidate->args, 927 COERCION_IMPLICIT)) 928 { 929 current_candidate->next = *candidates; 930 *candidates = current_candidate; 931 ncandidates++; 932 } 933 } 934 935 return ncandidates; 936 } /* func_match_argtypes() */ 937 938 939 /* func_select_candidate() 940 * Given the input argtype array and more than one candidate 941 * for the function, attempt to resolve the conflict. 942 * 943 * Returns the selected candidate if the conflict can be resolved, 944 * otherwise returns NULL. 945 * 946 * Note that the caller has already determined that there is no candidate 947 * exactly matching the input argtypes, and has pruned away any "candidates" 948 * that aren't actually coercion-compatible with the input types. 949 * 950 * This is also used for resolving ambiguous operator references. Formerly 951 * parse_oper.c had its own, essentially duplicate code for the purpose. 952 * The following comments (formerly in parse_oper.c) are kept to record some 953 * of the history of these heuristics. 954 * 955 * OLD COMMENTS: 956 * 957 * This routine is new code, replacing binary_oper_select_candidate() 958 * which dates from v4.2/v1.0.x days. It tries very hard to match up 959 * operators with types, including allowing type coercions if necessary. 960 * The important thing is that the code do as much as possible, 961 * while _never_ doing the wrong thing, where "the wrong thing" would 962 * be returning an operator when other better choices are available, 963 * or returning an operator which is a non-intuitive possibility. 964 * - thomas 1998-05-21 965 * 966 * The comments below came from binary_oper_select_candidate(), and 967 * illustrate the issues and choices which are possible: 968 * - thomas 1998-05-20 969 * 970 * current wisdom holds that the default operator should be one in which 971 * both operands have the same type (there will only be one such 972 * operator) 973 * 974 * 7.27.93 - I have decided not to do this; it's too hard to justify, and 975 * it's easy enough to typecast explicitly - avi 976 * [the rest of this routine was commented out since then - ay] 977 * 978 * 6/23/95 - I don't complete agree with avi. In particular, casting 979 * floats is a pain for users. Whatever the rationale behind not doing 980 * this is, I need the following special case to work. 981 * 982 * In the WHERE clause of a query, if a float is specified without 983 * quotes, we treat it as float8. I added the float48* operators so 984 * that we can operate on float4 and float8. But now we have more than 985 * one matching operator if the right arg is unknown (eg. float 986 * specified with quotes). This break some stuff in the regression 987 * test where there are floats in quotes not properly casted. Below is 988 * the solution. In addition to requiring the operator operates on the 989 * same type for both operands [as in the code Avi originally 990 * commented out], we also require that the operators be equivalent in 991 * some sense. (see equivalentOpersAfterPromotion for details.) 992 * - ay 6/95 993 */ 994 FuncCandidateList 995 func_select_candidate(int nargs, 996 Oid *input_typeids, 997 FuncCandidateList candidates) 998 { 999 FuncCandidateList current_candidate, 1000 first_candidate, 1001 last_candidate; 1002 Oid *current_typeids; 1003 Oid current_type; 1004 int i; 1005 int ncandidates; 1006 int nbestMatch, 1007 nmatch, 1008 nunknowns; 1009 Oid input_base_typeids[FUNC_MAX_ARGS]; 1010 TYPCATEGORY slot_category[FUNC_MAX_ARGS], 1011 current_category; 1012 bool current_is_preferred; 1013 bool slot_has_preferred_type[FUNC_MAX_ARGS]; 1014 bool resolved_unknowns; 1015 1016 /* protect local fixed-size arrays */ 1017 if (nargs > FUNC_MAX_ARGS) 1018 ereport(ERROR, 1019 (errcode(ERRCODE_TOO_MANY_ARGUMENTS), 1020 errmsg_plural("cannot pass more than %d argument to a function", 1021 "cannot pass more than %d arguments to a function", 1022 FUNC_MAX_ARGS, 1023 FUNC_MAX_ARGS))); 1024 1025 /* 1026 * If any input types are domains, reduce them to their base types. This 1027 * ensures that we will consider functions on the base type to be "exact 1028 * matches" in the exact-match heuristic; it also makes it possible to do 1029 * something useful with the type-category heuristics. Note that this 1030 * makes it difficult, but not impossible, to use functions declared to 1031 * take a domain as an input datatype. Such a function will be selected 1032 * over the base-type function only if it is an exact match at all 1033 * argument positions, and so was already chosen by our caller. 1034 * 1035 * While we're at it, count the number of unknown-type arguments for use 1036 * later. 1037 */ 1038 nunknowns = 0; 1039 for (i = 0; i < nargs; i++) 1040 { 1041 if (input_typeids[i] != UNKNOWNOID) 1042 input_base_typeids[i] = getBaseType(input_typeids[i]); 1043 else 1044 { 1045 /* no need to call getBaseType on UNKNOWNOID */ 1046 input_base_typeids[i] = UNKNOWNOID; 1047 nunknowns++; 1048 } 1049 } 1050 1051 /* 1052 * Run through all candidates and keep those with the most matches on 1053 * exact types. Keep all candidates if none match. 1054 */ 1055 ncandidates = 0; 1056 nbestMatch = 0; 1057 last_candidate = NULL; 1058 for (current_candidate = candidates; 1059 current_candidate != NULL; 1060 current_candidate = current_candidate->next) 1061 { 1062 current_typeids = current_candidate->args; 1063 nmatch = 0; 1064 for (i = 0; i < nargs; i++) 1065 { 1066 if (input_base_typeids[i] != UNKNOWNOID && 1067 current_typeids[i] == input_base_typeids[i]) 1068 nmatch++; 1069 } 1070 1071 /* take this one as the best choice so far? */ 1072 if ((nmatch > nbestMatch) || (last_candidate == NULL)) 1073 { 1074 nbestMatch = nmatch; 1075 candidates = current_candidate; 1076 last_candidate = current_candidate; 1077 ncandidates = 1; 1078 } 1079 /* no worse than the last choice, so keep this one too? */ 1080 else if (nmatch == nbestMatch) 1081 { 1082 last_candidate->next = current_candidate; 1083 last_candidate = current_candidate; 1084 ncandidates++; 1085 } 1086 /* otherwise, don't bother keeping this one... */ 1087 } 1088 1089 if (last_candidate) /* terminate rebuilt list */ 1090 last_candidate->next = NULL; 1091 1092 if (ncandidates == 1) 1093 return candidates; 1094 1095 /* 1096 * Still too many candidates? Now look for candidates which have either 1097 * exact matches or preferred types at the args that will require 1098 * coercion. (Restriction added in 7.4: preferred type must be of same 1099 * category as input type; give no preference to cross-category 1100 * conversions to preferred types.) Keep all candidates if none match. 1101 */ 1102 for (i = 0; i < nargs; i++) /* avoid multiple lookups */ 1103 slot_category[i] = TypeCategory(input_base_typeids[i]); 1104 ncandidates = 0; 1105 nbestMatch = 0; 1106 last_candidate = NULL; 1107 for (current_candidate = candidates; 1108 current_candidate != NULL; 1109 current_candidate = current_candidate->next) 1110 { 1111 current_typeids = current_candidate->args; 1112 nmatch = 0; 1113 for (i = 0; i < nargs; i++) 1114 { 1115 if (input_base_typeids[i] != UNKNOWNOID) 1116 { 1117 if (current_typeids[i] == input_base_typeids[i] || 1118 IsPreferredType(slot_category[i], current_typeids[i])) 1119 nmatch++; 1120 } 1121 } 1122 1123 if ((nmatch > nbestMatch) || (last_candidate == NULL)) 1124 { 1125 nbestMatch = nmatch; 1126 candidates = current_candidate; 1127 last_candidate = current_candidate; 1128 ncandidates = 1; 1129 } 1130 else if (nmatch == nbestMatch) 1131 { 1132 last_candidate->next = current_candidate; 1133 last_candidate = current_candidate; 1134 ncandidates++; 1135 } 1136 } 1137 1138 if (last_candidate) /* terminate rebuilt list */ 1139 last_candidate->next = NULL; 1140 1141 if (ncandidates == 1) 1142 return candidates; 1143 1144 /* 1145 * Still too many candidates? Try assigning types for the unknown inputs. 1146 * 1147 * If there are no unknown inputs, we have no more heuristics that apply, 1148 * and must fail. 1149 */ 1150 if (nunknowns == 0) 1151 return NULL; /* failed to select a best candidate */ 1152 1153 /* 1154 * The next step examines each unknown argument position to see if we can 1155 * determine a "type category" for it. If any candidate has an input 1156 * datatype of STRING category, use STRING category (this bias towards 1157 * STRING is appropriate since unknown-type literals look like strings). 1158 * Otherwise, if all the candidates agree on the type category of this 1159 * argument position, use that category. Otherwise, fail because we 1160 * cannot determine a category. 1161 * 1162 * If we are able to determine a type category, also notice whether any of 1163 * the candidates takes a preferred datatype within the category. 1164 * 1165 * Having completed this examination, remove candidates that accept the 1166 * wrong category at any unknown position. Also, if at least one 1167 * candidate accepted a preferred type at a position, remove candidates 1168 * that accept non-preferred types. If just one candidate remains, return 1169 * that one. However, if this rule turns out to reject all candidates, 1170 * keep them all instead. 1171 */ 1172 resolved_unknowns = false; 1173 for (i = 0; i < nargs; i++) 1174 { 1175 bool have_conflict; 1176 1177 if (input_base_typeids[i] != UNKNOWNOID) 1178 continue; 1179 resolved_unknowns = true; /* assume we can do it */ 1180 slot_category[i] = TYPCATEGORY_INVALID; 1181 slot_has_preferred_type[i] = false; 1182 have_conflict = false; 1183 for (current_candidate = candidates; 1184 current_candidate != NULL; 1185 current_candidate = current_candidate->next) 1186 { 1187 current_typeids = current_candidate->args; 1188 current_type = current_typeids[i]; 1189 get_type_category_preferred(current_type, 1190 ¤t_category, 1191 ¤t_is_preferred); 1192 if (slot_category[i] == TYPCATEGORY_INVALID) 1193 { 1194 /* first candidate */ 1195 slot_category[i] = current_category; 1196 slot_has_preferred_type[i] = current_is_preferred; 1197 } 1198 else if (current_category == slot_category[i]) 1199 { 1200 /* more candidates in same category */ 1201 slot_has_preferred_type[i] |= current_is_preferred; 1202 } 1203 else 1204 { 1205 /* category conflict! */ 1206 if (current_category == TYPCATEGORY_STRING) 1207 { 1208 /* STRING always wins if available */ 1209 slot_category[i] = current_category; 1210 slot_has_preferred_type[i] = current_is_preferred; 1211 } 1212 else 1213 { 1214 /* 1215 * Remember conflict, but keep going (might find STRING) 1216 */ 1217 have_conflict = true; 1218 } 1219 } 1220 } 1221 if (have_conflict && slot_category[i] != TYPCATEGORY_STRING) 1222 { 1223 /* Failed to resolve category conflict at this position */ 1224 resolved_unknowns = false; 1225 break; 1226 } 1227 } 1228 1229 if (resolved_unknowns) 1230 { 1231 /* Strip non-matching candidates */ 1232 ncandidates = 0; 1233 first_candidate = candidates; 1234 last_candidate = NULL; 1235 for (current_candidate = candidates; 1236 current_candidate != NULL; 1237 current_candidate = current_candidate->next) 1238 { 1239 bool keepit = true; 1240 1241 current_typeids = current_candidate->args; 1242 for (i = 0; i < nargs; i++) 1243 { 1244 if (input_base_typeids[i] != UNKNOWNOID) 1245 continue; 1246 current_type = current_typeids[i]; 1247 get_type_category_preferred(current_type, 1248 ¤t_category, 1249 ¤t_is_preferred); 1250 if (current_category != slot_category[i]) 1251 { 1252 keepit = false; 1253 break; 1254 } 1255 if (slot_has_preferred_type[i] && !current_is_preferred) 1256 { 1257 keepit = false; 1258 break; 1259 } 1260 } 1261 if (keepit) 1262 { 1263 /* keep this candidate */ 1264 last_candidate = current_candidate; 1265 ncandidates++; 1266 } 1267 else 1268 { 1269 /* forget this candidate */ 1270 if (last_candidate) 1271 last_candidate->next = current_candidate->next; 1272 else 1273 first_candidate = current_candidate->next; 1274 } 1275 } 1276 1277 /* if we found any matches, restrict our attention to those */ 1278 if (last_candidate) 1279 { 1280 candidates = first_candidate; 1281 /* terminate rebuilt list */ 1282 last_candidate->next = NULL; 1283 } 1284 1285 if (ncandidates == 1) 1286 return candidates; 1287 } 1288 1289 /* 1290 * Last gasp: if there are both known- and unknown-type inputs, and all 1291 * the known types are the same, assume the unknown inputs are also that 1292 * type, and see if that gives us a unique match. If so, use that match. 1293 * 1294 * NOTE: for a binary operator with one unknown and one non-unknown input, 1295 * we already tried this heuristic in binary_oper_exact(). However, that 1296 * code only finds exact matches, whereas here we will handle matches that 1297 * involve coercion, polymorphic type resolution, etc. 1298 */ 1299 if (nunknowns < nargs) 1300 { 1301 Oid known_type = UNKNOWNOID; 1302 1303 for (i = 0; i < nargs; i++) 1304 { 1305 if (input_base_typeids[i] == UNKNOWNOID) 1306 continue; 1307 if (known_type == UNKNOWNOID) /* first known arg? */ 1308 known_type = input_base_typeids[i]; 1309 else if (known_type != input_base_typeids[i]) 1310 { 1311 /* oops, not all match */ 1312 known_type = UNKNOWNOID; 1313 break; 1314 } 1315 } 1316 1317 if (known_type != UNKNOWNOID) 1318 { 1319 /* okay, just one known type, apply the heuristic */ 1320 for (i = 0; i < nargs; i++) 1321 input_base_typeids[i] = known_type; 1322 ncandidates = 0; 1323 last_candidate = NULL; 1324 for (current_candidate = candidates; 1325 current_candidate != NULL; 1326 current_candidate = current_candidate->next) 1327 { 1328 current_typeids = current_candidate->args; 1329 if (can_coerce_type(nargs, input_base_typeids, current_typeids, 1330 COERCION_IMPLICIT)) 1331 { 1332 if (++ncandidates > 1) 1333 break; /* not unique, give up */ 1334 last_candidate = current_candidate; 1335 } 1336 } 1337 if (ncandidates == 1) 1338 { 1339 /* successfully identified a unique match */ 1340 last_candidate->next = NULL; 1341 return last_candidate; 1342 } 1343 } 1344 } 1345 1346 return NULL; /* failed to select a best candidate */ 1347 } /* func_select_candidate() */ 1348 1349 1350 /* func_get_detail() 1351 * 1352 * Find the named function in the system catalogs. 1353 * 1354 * Attempt to find the named function in the system catalogs with 1355 * arguments exactly as specified, so that the normal case (exact match) 1356 * is as quick as possible. 1357 * 1358 * If an exact match isn't found: 1359 * 1) check for possible interpretation as a type coercion request 1360 * 2) apply the ambiguous-function resolution rules 1361 * 1362 * Return values *funcid through *true_typeids receive info about the function. 1363 * If argdefaults isn't NULL, *argdefaults receives a list of any default 1364 * argument expressions that need to be added to the given arguments. 1365 * 1366 * When processing a named- or mixed-notation call (ie, fargnames isn't NIL), 1367 * the returned true_typeids and argdefaults are ordered according to the 1368 * call's argument ordering: first any positional arguments, then the named 1369 * arguments, then defaulted arguments (if needed and allowed by 1370 * expand_defaults). Some care is needed if this information is to be compared 1371 * to the function's pg_proc entry, but in practice the caller can usually 1372 * just work with the call's argument ordering. 1373 * 1374 * We rely primarily on fargnames/nargs/argtypes as the argument description. 1375 * The actual expression node list is passed in fargs so that we can check 1376 * for type coercion of a constant. Some callers pass fargs == NIL indicating 1377 * they don't need that check made. Note also that when fargnames isn't NIL, 1378 * the fargs list must be passed if the caller wants actual argument position 1379 * information to be returned into the NamedArgExpr nodes. 1380 */ 1381 FuncDetailCode 1382 func_get_detail(List *funcname, 1383 List *fargs, 1384 List *fargnames, 1385 int nargs, 1386 Oid *argtypes, 1387 bool expand_variadic, 1388 bool expand_defaults, 1389 Oid *funcid, /* return value */ 1390 Oid *rettype, /* return value */ 1391 bool *retset, /* return value */ 1392 int *nvargs, /* return value */ 1393 Oid *vatype, /* return value */ 1394 Oid **true_typeids, /* return value */ 1395 List **argdefaults) /* optional return value */ 1396 { 1397 FuncCandidateList raw_candidates; 1398 FuncCandidateList best_candidate; 1399 1400 /* initialize output arguments to silence compiler warnings */ 1401 *funcid = InvalidOid; 1402 *rettype = InvalidOid; 1403 *retset = false; 1404 *nvargs = 0; 1405 *vatype = InvalidOid; 1406 *true_typeids = NULL; 1407 if (argdefaults) 1408 *argdefaults = NIL; 1409 1410 /* Get list of possible candidates from namespace search */ 1411 raw_candidates = FuncnameGetCandidates(funcname, nargs, fargnames, 1412 expand_variadic, expand_defaults, 1413 false); 1414 1415 /* 1416 * Quickly check if there is an exact match to the input datatypes (there 1417 * can be only one) 1418 */ 1419 for (best_candidate = raw_candidates; 1420 best_candidate != NULL; 1421 best_candidate = best_candidate->next) 1422 { 1423 /* if nargs==0, argtypes can be null; don't pass that to memcmp */ 1424 if (nargs == 0 || 1425 memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0) 1426 break; 1427 } 1428 1429 if (best_candidate == NULL) 1430 { 1431 /* 1432 * If we didn't find an exact match, next consider the possibility 1433 * that this is really a type-coercion request: a single-argument 1434 * function call where the function name is a type name. If so, and 1435 * if the coercion path is RELABELTYPE or COERCEVIAIO, then go ahead 1436 * and treat the "function call" as a coercion. 1437 * 1438 * This interpretation needs to be given higher priority than 1439 * interpretations involving a type coercion followed by a function 1440 * call, otherwise we can produce surprising results. For example, we 1441 * want "text(varchar)" to be interpreted as a simple coercion, not as 1442 * "text(name(varchar))" which the code below this point is entirely 1443 * capable of selecting. 1444 * 1445 * We also treat a coercion of a previously-unknown-type literal 1446 * constant to a specific type this way. 1447 * 1448 * The reason we reject COERCION_PATH_FUNC here is that we expect the 1449 * cast implementation function to be named after the target type. 1450 * Thus the function will be found by normal lookup if appropriate. 1451 * 1452 * The reason we reject COERCION_PATH_ARRAYCOERCE is mainly that you 1453 * can't write "foo[] (something)" as a function call. In theory 1454 * someone might want to invoke it as "_foo (something)" but we have 1455 * never supported that historically, so we can insist that people 1456 * write it as a normal cast instead. 1457 * 1458 * We also reject the specific case of COERCEVIAIO for a composite 1459 * source type and a string-category target type. This is a case that 1460 * find_coercion_pathway() allows by default, but experience has shown 1461 * that it's too commonly invoked by mistake. So, again, insist that 1462 * people use cast syntax if they want to do that. 1463 * 1464 * NB: it's important that this code does not exceed what coerce_type 1465 * can do, because the caller will try to apply coerce_type if we 1466 * return FUNCDETAIL_COERCION. If we return that result for something 1467 * coerce_type can't handle, we'll cause infinite recursion between 1468 * this module and coerce_type! 1469 */ 1470 if (nargs == 1 && fargs != NIL && fargnames == NIL) 1471 { 1472 Oid targetType = FuncNameAsType(funcname); 1473 1474 if (OidIsValid(targetType)) 1475 { 1476 Oid sourceType = argtypes[0]; 1477 Node *arg1 = linitial(fargs); 1478 bool iscoercion; 1479 1480 if (sourceType == UNKNOWNOID && IsA(arg1, Const)) 1481 { 1482 /* always treat typename('literal') as coercion */ 1483 iscoercion = true; 1484 } 1485 else 1486 { 1487 CoercionPathType cpathtype; 1488 Oid cfuncid; 1489 1490 cpathtype = find_coercion_pathway(targetType, sourceType, 1491 COERCION_EXPLICIT, 1492 &cfuncid); 1493 switch (cpathtype) 1494 { 1495 case COERCION_PATH_RELABELTYPE: 1496 iscoercion = true; 1497 break; 1498 case COERCION_PATH_COERCEVIAIO: 1499 if ((sourceType == RECORDOID || 1500 ISCOMPLEX(sourceType)) && 1501 TypeCategory(targetType) == TYPCATEGORY_STRING) 1502 iscoercion = false; 1503 else 1504 iscoercion = true; 1505 break; 1506 default: 1507 iscoercion = false; 1508 break; 1509 } 1510 } 1511 1512 if (iscoercion) 1513 { 1514 /* Treat it as a type coercion */ 1515 *funcid = InvalidOid; 1516 *rettype = targetType; 1517 *retset = false; 1518 *nvargs = 0; 1519 *vatype = InvalidOid; 1520 *true_typeids = argtypes; 1521 return FUNCDETAIL_COERCION; 1522 } 1523 } 1524 } 1525 1526 /* 1527 * didn't find an exact match, so now try to match up candidates... 1528 */ 1529 if (raw_candidates != NULL) 1530 { 1531 FuncCandidateList current_candidates; 1532 int ncandidates; 1533 1534 ncandidates = func_match_argtypes(nargs, 1535 argtypes, 1536 raw_candidates, 1537 ¤t_candidates); 1538 1539 /* one match only? then run with it... */ 1540 if (ncandidates == 1) 1541 best_candidate = current_candidates; 1542 1543 /* 1544 * multiple candidates? then better decide or throw an error... 1545 */ 1546 else if (ncandidates > 1) 1547 { 1548 best_candidate = func_select_candidate(nargs, 1549 argtypes, 1550 current_candidates); 1551 1552 /* 1553 * If we were able to choose a best candidate, we're done. 1554 * Otherwise, ambiguous function call. 1555 */ 1556 if (!best_candidate) 1557 return FUNCDETAIL_MULTIPLE; 1558 } 1559 } 1560 } 1561 1562 if (best_candidate) 1563 { 1564 HeapTuple ftup; 1565 Form_pg_proc pform; 1566 FuncDetailCode result; 1567 1568 /* 1569 * If processing named args or expanding variadics or defaults, the 1570 * "best candidate" might represent multiple equivalently good 1571 * functions; treat this case as ambiguous. 1572 */ 1573 if (!OidIsValid(best_candidate->oid)) 1574 return FUNCDETAIL_MULTIPLE; 1575 1576 /* 1577 * We disallow VARIADIC with named arguments unless the last argument 1578 * (the one with VARIADIC attached) actually matched the variadic 1579 * parameter. This is mere pedantry, really, but some folks insisted. 1580 */ 1581 if (fargnames != NIL && !expand_variadic && nargs > 0 && 1582 best_candidate->argnumbers[nargs - 1] != nargs - 1) 1583 return FUNCDETAIL_NOTFOUND; 1584 1585 *funcid = best_candidate->oid; 1586 *nvargs = best_candidate->nvargs; 1587 *true_typeids = best_candidate->args; 1588 1589 /* 1590 * If processing named args, return actual argument positions into 1591 * NamedArgExpr nodes in the fargs list. This is a bit ugly but not 1592 * worth the extra notation needed to do it differently. 1593 */ 1594 if (best_candidate->argnumbers != NULL) 1595 { 1596 int i = 0; 1597 ListCell *lc; 1598 1599 foreach(lc, fargs) 1600 { 1601 NamedArgExpr *na = (NamedArgExpr *) lfirst(lc); 1602 1603 if (IsA(na, NamedArgExpr)) 1604 na->argnumber = best_candidate->argnumbers[i]; 1605 i++; 1606 } 1607 } 1608 1609 ftup = SearchSysCache1(PROCOID, 1610 ObjectIdGetDatum(best_candidate->oid)); 1611 if (!HeapTupleIsValid(ftup)) /* should not happen */ 1612 elog(ERROR, "cache lookup failed for function %u", 1613 best_candidate->oid); 1614 pform = (Form_pg_proc) GETSTRUCT(ftup); 1615 *rettype = pform->prorettype; 1616 *retset = pform->proretset; 1617 *vatype = pform->provariadic; 1618 /* fetch default args if caller wants 'em */ 1619 if (argdefaults && best_candidate->ndargs > 0) 1620 { 1621 Datum proargdefaults; 1622 bool isnull; 1623 char *str; 1624 List *defaults; 1625 1626 /* shouldn't happen, FuncnameGetCandidates messed up */ 1627 if (best_candidate->ndargs > pform->pronargdefaults) 1628 elog(ERROR, "not enough default arguments"); 1629 1630 proargdefaults = SysCacheGetAttr(PROCOID, ftup, 1631 Anum_pg_proc_proargdefaults, 1632 &isnull); 1633 Assert(!isnull); 1634 str = TextDatumGetCString(proargdefaults); 1635 defaults = castNode(List, stringToNode(str)); 1636 pfree(str); 1637 1638 /* Delete any unused defaults from the returned list */ 1639 if (best_candidate->argnumbers != NULL) 1640 { 1641 /* 1642 * This is a bit tricky in named notation, since the supplied 1643 * arguments could replace any subset of the defaults. We 1644 * work by making a bitmapset of the argnumbers of defaulted 1645 * arguments, then scanning the defaults list and selecting 1646 * the needed items. (This assumes that defaulted arguments 1647 * should be supplied in their positional order.) 1648 */ 1649 Bitmapset *defargnumbers; 1650 int *firstdefarg; 1651 List *newdefaults; 1652 ListCell *lc; 1653 int i; 1654 1655 defargnumbers = NULL; 1656 firstdefarg = &best_candidate->argnumbers[best_candidate->nargs - best_candidate->ndargs]; 1657 for (i = 0; i < best_candidate->ndargs; i++) 1658 defargnumbers = bms_add_member(defargnumbers, 1659 firstdefarg[i]); 1660 newdefaults = NIL; 1661 i = pform->pronargs - pform->pronargdefaults; 1662 foreach(lc, defaults) 1663 { 1664 if (bms_is_member(i, defargnumbers)) 1665 newdefaults = lappend(newdefaults, lfirst(lc)); 1666 i++; 1667 } 1668 Assert(list_length(newdefaults) == best_candidate->ndargs); 1669 bms_free(defargnumbers); 1670 *argdefaults = newdefaults; 1671 } 1672 else 1673 { 1674 /* 1675 * Defaults for positional notation are lots easier; just 1676 * remove any unwanted ones from the front. 1677 */ 1678 int ndelete; 1679 1680 ndelete = list_length(defaults) - best_candidate->ndargs; 1681 if (ndelete > 0) 1682 defaults = list_delete_first_n(defaults, ndelete); 1683 *argdefaults = defaults; 1684 } 1685 } 1686 1687 switch (pform->prokind) 1688 { 1689 case PROKIND_AGGREGATE: 1690 result = FUNCDETAIL_AGGREGATE; 1691 break; 1692 case PROKIND_FUNCTION: 1693 result = FUNCDETAIL_NORMAL; 1694 break; 1695 case PROKIND_PROCEDURE: 1696 result = FUNCDETAIL_PROCEDURE; 1697 break; 1698 case PROKIND_WINDOW: 1699 result = FUNCDETAIL_WINDOWFUNC; 1700 break; 1701 default: 1702 elog(ERROR, "unrecognized prokind: %c", pform->prokind); 1703 result = FUNCDETAIL_NORMAL; /* keep compiler quiet */ 1704 break; 1705 } 1706 1707 ReleaseSysCache(ftup); 1708 return result; 1709 } 1710 1711 return FUNCDETAIL_NOTFOUND; 1712 } 1713 1714 1715 /* 1716 * unify_hypothetical_args() 1717 * 1718 * Ensure that each hypothetical direct argument of a hypothetical-set 1719 * aggregate has the same type as the corresponding aggregated argument. 1720 * Modify the expressions in the fargs list, if necessary, and update 1721 * actual_arg_types[]. 1722 * 1723 * If the agg declared its args non-ANY (even ANYELEMENT), we need only a 1724 * sanity check that the declared types match; make_fn_arguments will coerce 1725 * the actual arguments to match the declared ones. But if the declaration 1726 * is ANY, nothing will happen in make_fn_arguments, so we need to fix any 1727 * mismatch here. We use the same type resolution logic as UNION etc. 1728 */ 1729 static void 1730 unify_hypothetical_args(ParseState *pstate, 1731 List *fargs, 1732 int numAggregatedArgs, 1733 Oid *actual_arg_types, 1734 Oid *declared_arg_types) 1735 { 1736 int numDirectArgs, 1737 numNonHypotheticalArgs; 1738 int hargpos; 1739 1740 numDirectArgs = list_length(fargs) - numAggregatedArgs; 1741 numNonHypotheticalArgs = numDirectArgs - numAggregatedArgs; 1742 /* safety check (should only trigger with a misdeclared agg) */ 1743 if (numNonHypotheticalArgs < 0) 1744 elog(ERROR, "incorrect number of arguments to hypothetical-set aggregate"); 1745 1746 /* Check each hypothetical arg and corresponding aggregated arg */ 1747 for (hargpos = numNonHypotheticalArgs; hargpos < numDirectArgs; hargpos++) 1748 { 1749 int aargpos = numDirectArgs + (hargpos - numNonHypotheticalArgs); 1750 ListCell *harg = list_nth_cell(fargs, hargpos); 1751 ListCell *aarg = list_nth_cell(fargs, aargpos); 1752 Oid commontype; 1753 1754 /* A mismatch means AggregateCreate didn't check properly ... */ 1755 if (declared_arg_types[hargpos] != declared_arg_types[aargpos]) 1756 elog(ERROR, "hypothetical-set aggregate has inconsistent declared argument types"); 1757 1758 /* No need to unify if make_fn_arguments will coerce */ 1759 if (declared_arg_types[hargpos] != ANYOID) 1760 continue; 1761 1762 /* 1763 * Select common type, giving preference to the aggregated argument's 1764 * type (we'd rather coerce the direct argument once than coerce all 1765 * the aggregated values). 1766 */ 1767 commontype = select_common_type(pstate, 1768 list_make2(lfirst(aarg), lfirst(harg)), 1769 "WITHIN GROUP", 1770 NULL); 1771 1772 /* 1773 * Perform the coercions. We don't need to worry about NamedArgExprs 1774 * here because they aren't supported with aggregates. 1775 */ 1776 lfirst(harg) = coerce_type(pstate, 1777 (Node *) lfirst(harg), 1778 actual_arg_types[hargpos], 1779 commontype, -1, 1780 COERCION_IMPLICIT, 1781 COERCE_IMPLICIT_CAST, 1782 -1); 1783 actual_arg_types[hargpos] = commontype; 1784 lfirst(aarg) = coerce_type(pstate, 1785 (Node *) lfirst(aarg), 1786 actual_arg_types[aargpos], 1787 commontype, -1, 1788 COERCION_IMPLICIT, 1789 COERCE_IMPLICIT_CAST, 1790 -1); 1791 actual_arg_types[aargpos] = commontype; 1792 } 1793 } 1794 1795 1796 /* 1797 * make_fn_arguments() 1798 * 1799 * Given the actual argument expressions for a function, and the desired 1800 * input types for the function, add any necessary typecasting to the 1801 * expression tree. Caller should already have verified that casting is 1802 * allowed. 1803 * 1804 * Caution: given argument list is modified in-place. 1805 * 1806 * As with coerce_type, pstate may be NULL if no special unknown-Param 1807 * processing is wanted. 1808 */ 1809 void 1810 make_fn_arguments(ParseState *pstate, 1811 List *fargs, 1812 Oid *actual_arg_types, 1813 Oid *declared_arg_types) 1814 { 1815 ListCell *current_fargs; 1816 int i = 0; 1817 1818 foreach(current_fargs, fargs) 1819 { 1820 /* types don't match? then force coercion using a function call... */ 1821 if (actual_arg_types[i] != declared_arg_types[i]) 1822 { 1823 Node *node = (Node *) lfirst(current_fargs); 1824 1825 /* 1826 * If arg is a NamedArgExpr, coerce its input expr instead --- we 1827 * want the NamedArgExpr to stay at the top level of the list. 1828 */ 1829 if (IsA(node, NamedArgExpr)) 1830 { 1831 NamedArgExpr *na = (NamedArgExpr *) node; 1832 1833 node = coerce_type(pstate, 1834 (Node *) na->arg, 1835 actual_arg_types[i], 1836 declared_arg_types[i], -1, 1837 COERCION_IMPLICIT, 1838 COERCE_IMPLICIT_CAST, 1839 -1); 1840 na->arg = (Expr *) node; 1841 } 1842 else 1843 { 1844 node = coerce_type(pstate, 1845 node, 1846 actual_arg_types[i], 1847 declared_arg_types[i], -1, 1848 COERCION_IMPLICIT, 1849 COERCE_IMPLICIT_CAST, 1850 -1); 1851 lfirst(current_fargs) = node; 1852 } 1853 } 1854 i++; 1855 } 1856 } 1857 1858 /* 1859 * FuncNameAsType - 1860 * convenience routine to see if a function name matches a type name 1861 * 1862 * Returns the OID of the matching type, or InvalidOid if none. We ignore 1863 * shell types and complex types. 1864 */ 1865 static Oid 1866 FuncNameAsType(List *funcname) 1867 { 1868 Oid result; 1869 Type typtup; 1870 1871 /* 1872 * temp_ok=false protects the <refsect1 id="sql-createfunction-security"> 1873 * contract for writing SECURITY DEFINER functions safely. 1874 */ 1875 typtup = LookupTypeNameExtended(NULL, makeTypeNameFromNameList(funcname), 1876 NULL, false, false); 1877 if (typtup == NULL) 1878 return InvalidOid; 1879 1880 if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined && 1881 !OidIsValid(typeTypeRelid(typtup))) 1882 result = typeTypeId(typtup); 1883 else 1884 result = InvalidOid; 1885 1886 ReleaseSysCache(typtup); 1887 return result; 1888 } 1889 1890 /* 1891 * ParseComplexProjection - 1892 * handles function calls with a single argument that is of complex type. 1893 * If the function call is actually a column projection, return a suitably 1894 * transformed expression tree. If not, return NULL. 1895 */ 1896 static Node * 1897 ParseComplexProjection(ParseState *pstate, const char *funcname, Node *first_arg, 1898 int location) 1899 { 1900 TupleDesc tupdesc; 1901 int i; 1902 1903 /* 1904 * Special case for whole-row Vars so that we can resolve (foo.*).bar even 1905 * when foo is a reference to a subselect, join, or RECORD function. A 1906 * bonus is that we avoid generating an unnecessary FieldSelect; our 1907 * result can omit the whole-row Var and just be a Var for the selected 1908 * field. 1909 * 1910 * This case could be handled by expandRecordVariable, but it's more 1911 * efficient to do it this way when possible. 1912 */ 1913 if (IsA(first_arg, Var) && 1914 ((Var *) first_arg)->varattno == InvalidAttrNumber) 1915 { 1916 ParseNamespaceItem *nsitem; 1917 1918 nsitem = GetNSItemByRangeTablePosn(pstate, 1919 ((Var *) first_arg)->varno, 1920 ((Var *) first_arg)->varlevelsup); 1921 /* Return a Var if funcname matches a column, else NULL */ 1922 return scanNSItemForColumn(pstate, nsitem, 1923 ((Var *) first_arg)->varlevelsup, 1924 funcname, location); 1925 } 1926 1927 /* 1928 * Else do it the hard way with get_expr_result_tupdesc(). 1929 * 1930 * If it's a Var of type RECORD, we have to work even harder: we have to 1931 * find what the Var refers to, and pass that to get_expr_result_tupdesc. 1932 * That task is handled by expandRecordVariable(). 1933 */ 1934 if (IsA(first_arg, Var) && 1935 ((Var *) first_arg)->vartype == RECORDOID) 1936 tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0); 1937 else 1938 tupdesc = get_expr_result_tupdesc(first_arg, true); 1939 if (!tupdesc) 1940 return NULL; /* unresolvable RECORD type */ 1941 1942 for (i = 0; i < tupdesc->natts; i++) 1943 { 1944 Form_pg_attribute att = TupleDescAttr(tupdesc, i); 1945 1946 if (strcmp(funcname, NameStr(att->attname)) == 0 && 1947 !att->attisdropped) 1948 { 1949 /* Success, so generate a FieldSelect expression */ 1950 FieldSelect *fselect = makeNode(FieldSelect); 1951 1952 fselect->arg = (Expr *) first_arg; 1953 fselect->fieldnum = i + 1; 1954 fselect->resulttype = att->atttypid; 1955 fselect->resulttypmod = att->atttypmod; 1956 /* save attribute's collation for parse_collate.c */ 1957 fselect->resultcollid = att->attcollation; 1958 return (Node *) fselect; 1959 } 1960 } 1961 1962 return NULL; /* funcname does not match any column */ 1963 } 1964 1965 /* 1966 * funcname_signature_string 1967 * Build a string representing a function name, including arg types. 1968 * The result is something like "foo(integer)". 1969 * 1970 * If argnames isn't NIL, it is a list of C strings representing the actual 1971 * arg names for the last N arguments. This must be considered part of the 1972 * function signature too, when dealing with named-notation function calls. 1973 * 1974 * This is typically used in the construction of function-not-found error 1975 * messages. 1976 */ 1977 const char * 1978 funcname_signature_string(const char *funcname, int nargs, 1979 List *argnames, const Oid *argtypes) 1980 { 1981 StringInfoData argbuf; 1982 int numposargs; 1983 ListCell *lc; 1984 int i; 1985 1986 initStringInfo(&argbuf); 1987 1988 appendStringInfo(&argbuf, "%s(", funcname); 1989 1990 numposargs = nargs - list_length(argnames); 1991 lc = list_head(argnames); 1992 1993 for (i = 0; i < nargs; i++) 1994 { 1995 if (i) 1996 appendStringInfoString(&argbuf, ", "); 1997 if (i >= numposargs) 1998 { 1999 appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc)); 2000 lc = lnext(argnames, lc); 2001 } 2002 appendStringInfoString(&argbuf, format_type_be(argtypes[i])); 2003 } 2004 2005 appendStringInfoChar(&argbuf, ')'); 2006 2007 return argbuf.data; /* return palloc'd string buffer */ 2008 } 2009 2010 /* 2011 * func_signature_string 2012 * As above, but function name is passed as a qualified name list. 2013 */ 2014 const char * 2015 func_signature_string(List *funcname, int nargs, 2016 List *argnames, const Oid *argtypes) 2017 { 2018 return funcname_signature_string(NameListToString(funcname), 2019 nargs, argnames, argtypes); 2020 } 2021 2022 /* 2023 * LookupFuncNameInternal 2024 * Workhorse for LookupFuncName/LookupFuncWithArgs 2025 * 2026 * In an error situation, e.g. can't find the function, then we return 2027 * InvalidOid and set *lookupError to indicate what went wrong. 2028 * 2029 * Possible errors: 2030 * FUNCLOOKUP_NOSUCHFUNC: we can't find a function of this name. 2031 * FUNCLOOKUP_AMBIGUOUS: nargs == -1 and more than one function matches. 2032 */ 2033 static Oid 2034 LookupFuncNameInternal(List *funcname, int nargs, const Oid *argtypes, 2035 bool missing_ok, FuncLookupError *lookupError) 2036 { 2037 FuncCandidateList clist; 2038 2039 /* NULL argtypes allowed for nullary functions only */ 2040 Assert(argtypes != NULL || nargs == 0); 2041 2042 /* Always set *lookupError, to forestall uninitialized-variable warnings */ 2043 *lookupError = FUNCLOOKUP_NOSUCHFUNC; 2044 2045 clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false, 2046 missing_ok); 2047 2048 /* 2049 * If no arguments were specified, the name must yield a unique candidate. 2050 */ 2051 if (nargs < 0) 2052 { 2053 if (clist) 2054 { 2055 /* If there is a second match then it's ambiguous */ 2056 if (clist->next) 2057 { 2058 *lookupError = FUNCLOOKUP_AMBIGUOUS; 2059 return InvalidOid; 2060 } 2061 /* Otherwise return the match */ 2062 return clist->oid; 2063 } 2064 else 2065 return InvalidOid; 2066 } 2067 2068 /* 2069 * Otherwise, look for a match to the arg types. FuncnameGetCandidates 2070 * has ensured that there's at most one match in the returned list. 2071 */ 2072 while (clist) 2073 { 2074 /* if nargs==0, argtypes can be null; don't pass that to memcmp */ 2075 if (nargs == 0 || 2076 memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0) 2077 return clist->oid; 2078 clist = clist->next; 2079 } 2080 2081 return InvalidOid; 2082 } 2083 2084 /* 2085 * LookupFuncName 2086 * 2087 * Given a possibly-qualified function name and optionally a set of argument 2088 * types, look up the function. Pass nargs == -1 to indicate that the number 2089 * and types of the arguments are unspecified (this is NOT the same as 2090 * specifying that there are no arguments). 2091 * 2092 * If the function name is not schema-qualified, it is sought in the current 2093 * namespace search path. 2094 * 2095 * If the function is not found, we return InvalidOid if missing_ok is true, 2096 * else raise an error. 2097 * 2098 * If nargs == -1 and multiple functions are found matching this function name 2099 * we will raise an ambiguous-function error, regardless of what missing_ok is 2100 * set to. 2101 */ 2102 Oid 2103 LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool missing_ok) 2104 { 2105 Oid funcoid; 2106 FuncLookupError lookupError; 2107 2108 funcoid = LookupFuncNameInternal(funcname, nargs, argtypes, missing_ok, 2109 &lookupError); 2110 2111 if (OidIsValid(funcoid)) 2112 return funcoid; 2113 2114 switch (lookupError) 2115 { 2116 case FUNCLOOKUP_NOSUCHFUNC: 2117 /* Let the caller deal with it when missing_ok is true */ 2118 if (missing_ok) 2119 return InvalidOid; 2120 2121 if (nargs < 0) 2122 ereport(ERROR, 2123 (errcode(ERRCODE_UNDEFINED_FUNCTION), 2124 errmsg("could not find a function named \"%s\"", 2125 NameListToString(funcname)))); 2126 else 2127 ereport(ERROR, 2128 (errcode(ERRCODE_UNDEFINED_FUNCTION), 2129 errmsg("function %s does not exist", 2130 func_signature_string(funcname, nargs, 2131 NIL, argtypes)))); 2132 break; 2133 2134 case FUNCLOOKUP_AMBIGUOUS: 2135 /* Raise an error regardless of missing_ok */ 2136 ereport(ERROR, 2137 (errcode(ERRCODE_AMBIGUOUS_FUNCTION), 2138 errmsg("function name \"%s\" is not unique", 2139 NameListToString(funcname)), 2140 errhint("Specify the argument list to select the function unambiguously."))); 2141 break; 2142 } 2143 2144 return InvalidOid; /* Keep compiler quiet */ 2145 } 2146 2147 /* 2148 * LookupFuncWithArgs 2149 * 2150 * Like LookupFuncName, but the argument types are specified by an 2151 * ObjectWithArgs node. Also, this function can check whether the result is a 2152 * function, procedure, or aggregate, based on the objtype argument. Pass 2153 * OBJECT_ROUTINE to accept any of them. 2154 * 2155 * For historical reasons, we also accept aggregates when looking for a 2156 * function. 2157 * 2158 * When missing_ok is true we don't generate any error for missing objects and 2159 * return InvalidOid. Other types of errors can still be raised, regardless 2160 * of the value of missing_ok. 2161 */ 2162 Oid 2163 LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool missing_ok) 2164 { 2165 Oid argoids[FUNC_MAX_ARGS]; 2166 int argcount; 2167 int nargs; 2168 int i; 2169 ListCell *args_item; 2170 Oid oid; 2171 FuncLookupError lookupError; 2172 2173 Assert(objtype == OBJECT_AGGREGATE || 2174 objtype == OBJECT_FUNCTION || 2175 objtype == OBJECT_PROCEDURE || 2176 objtype == OBJECT_ROUTINE); 2177 2178 argcount = list_length(func->objargs); 2179 if (argcount > FUNC_MAX_ARGS) 2180 { 2181 if (objtype == OBJECT_PROCEDURE) 2182 ereport(ERROR, 2183 (errcode(ERRCODE_TOO_MANY_ARGUMENTS), 2184 errmsg_plural("procedures cannot have more than %d argument", 2185 "procedures cannot have more than %d arguments", 2186 FUNC_MAX_ARGS, 2187 FUNC_MAX_ARGS))); 2188 else 2189 ereport(ERROR, 2190 (errcode(ERRCODE_TOO_MANY_ARGUMENTS), 2191 errmsg_plural("functions cannot have more than %d argument", 2192 "functions cannot have more than %d arguments", 2193 FUNC_MAX_ARGS, 2194 FUNC_MAX_ARGS))); 2195 } 2196 2197 i = 0; 2198 foreach(args_item, func->objargs) 2199 { 2200 TypeName *t = (TypeName *) lfirst(args_item); 2201 2202 argoids[i] = LookupTypeNameOid(NULL, t, missing_ok); 2203 if (!OidIsValid(argoids[i])) 2204 return InvalidOid; /* missing_ok must be true */ 2205 i++; 2206 } 2207 2208 /* 2209 * Set nargs for LookupFuncNameInternal. It expects -1 to mean no args 2210 * were specified. 2211 */ 2212 nargs = func->args_unspecified ? -1 : argcount; 2213 2214 oid = LookupFuncNameInternal(func->objname, nargs, argoids, missing_ok, 2215 &lookupError); 2216 2217 if (OidIsValid(oid)) 2218 { 2219 /* 2220 * Even if we found the function, perform validation that the objtype 2221 * matches the prokind of the found function. For historical reasons 2222 * we allow the objtype of FUNCTION to include aggregates and window 2223 * functions; but we draw the line if the object is a procedure. That 2224 * is a new enough feature that this historical rule does not apply. 2225 */ 2226 switch (objtype) 2227 { 2228 case OBJECT_FUNCTION: 2229 /* Only complain if it's a procedure. */ 2230 if (get_func_prokind(oid) == PROKIND_PROCEDURE) 2231 ereport(ERROR, 2232 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 2233 errmsg("%s is not a function", 2234 func_signature_string(func->objname, argcount, 2235 NIL, argoids)))); 2236 break; 2237 2238 case OBJECT_PROCEDURE: 2239 /* Reject if found object is not a procedure. */ 2240 if (get_func_prokind(oid) != PROKIND_PROCEDURE) 2241 ereport(ERROR, 2242 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 2243 errmsg("%s is not a procedure", 2244 func_signature_string(func->objname, argcount, 2245 NIL, argoids)))); 2246 break; 2247 2248 case OBJECT_AGGREGATE: 2249 /* Reject if found object is not an aggregate. */ 2250 if (get_func_prokind(oid) != PROKIND_AGGREGATE) 2251 ereport(ERROR, 2252 (errcode(ERRCODE_WRONG_OBJECT_TYPE), 2253 errmsg("function %s is not an aggregate", 2254 func_signature_string(func->objname, argcount, 2255 NIL, argoids)))); 2256 break; 2257 2258 default: 2259 /* OBJECT_ROUTINE accepts anything. */ 2260 break; 2261 } 2262 2263 return oid; /* All good */ 2264 } 2265 else 2266 { 2267 /* Deal with cases where the lookup failed */ 2268 switch (lookupError) 2269 { 2270 case FUNCLOOKUP_NOSUCHFUNC: 2271 /* Suppress no-such-func errors when missing_ok is true */ 2272 if (missing_ok) 2273 break; 2274 2275 switch (objtype) 2276 { 2277 case OBJECT_PROCEDURE: 2278 if (func->args_unspecified) 2279 ereport(ERROR, 2280 (errcode(ERRCODE_UNDEFINED_FUNCTION), 2281 errmsg("could not find a procedure named \"%s\"", 2282 NameListToString(func->objname)))); 2283 else 2284 ereport(ERROR, 2285 (errcode(ERRCODE_UNDEFINED_FUNCTION), 2286 errmsg("procedure %s does not exist", 2287 func_signature_string(func->objname, argcount, 2288 NIL, argoids)))); 2289 break; 2290 2291 case OBJECT_AGGREGATE: 2292 if (func->args_unspecified) 2293 ereport(ERROR, 2294 (errcode(ERRCODE_UNDEFINED_FUNCTION), 2295 errmsg("could not find an aggregate named \"%s\"", 2296 NameListToString(func->objname)))); 2297 else if (argcount == 0) 2298 ereport(ERROR, 2299 (errcode(ERRCODE_UNDEFINED_FUNCTION), 2300 errmsg("aggregate %s(*) does not exist", 2301 NameListToString(func->objname)))); 2302 else 2303 ereport(ERROR, 2304 (errcode(ERRCODE_UNDEFINED_FUNCTION), 2305 errmsg("aggregate %s does not exist", 2306 func_signature_string(func->objname, argcount, 2307 NIL, argoids)))); 2308 break; 2309 2310 default: 2311 /* FUNCTION and ROUTINE */ 2312 if (func->args_unspecified) 2313 ereport(ERROR, 2314 (errcode(ERRCODE_UNDEFINED_FUNCTION), 2315 errmsg("could not find a function named \"%s\"", 2316 NameListToString(func->objname)))); 2317 else 2318 ereport(ERROR, 2319 (errcode(ERRCODE_UNDEFINED_FUNCTION), 2320 errmsg("function %s does not exist", 2321 func_signature_string(func->objname, argcount, 2322 NIL, argoids)))); 2323 break; 2324 } 2325 break; 2326 2327 case FUNCLOOKUP_AMBIGUOUS: 2328 switch (objtype) 2329 { 2330 case OBJECT_FUNCTION: 2331 ereport(ERROR, 2332 (errcode(ERRCODE_AMBIGUOUS_FUNCTION), 2333 errmsg("function name \"%s\" is not unique", 2334 NameListToString(func->objname)), 2335 errhint("Specify the argument list to select the function unambiguously."))); 2336 break; 2337 case OBJECT_PROCEDURE: 2338 ereport(ERROR, 2339 (errcode(ERRCODE_AMBIGUOUS_FUNCTION), 2340 errmsg("procedure name \"%s\" is not unique", 2341 NameListToString(func->objname)), 2342 errhint("Specify the argument list to select the procedure unambiguously."))); 2343 break; 2344 case OBJECT_AGGREGATE: 2345 ereport(ERROR, 2346 (errcode(ERRCODE_AMBIGUOUS_FUNCTION), 2347 errmsg("aggregate name \"%s\" is not unique", 2348 NameListToString(func->objname)), 2349 errhint("Specify the argument list to select the aggregate unambiguously."))); 2350 break; 2351 case OBJECT_ROUTINE: 2352 ereport(ERROR, 2353 (errcode(ERRCODE_AMBIGUOUS_FUNCTION), 2354 errmsg("routine name \"%s\" is not unique", 2355 NameListToString(func->objname)), 2356 errhint("Specify the argument list to select the routine unambiguously."))); 2357 break; 2358 2359 default: 2360 Assert(false); /* Disallowed by Assert above */ 2361 break; 2362 } 2363 break; 2364 } 2365 2366 return InvalidOid; 2367 } 2368 } 2369 2370 /* 2371 * check_srf_call_placement 2372 * Verify that a set-returning function is called in a valid place, 2373 * and throw a nice error if not. 2374 * 2375 * A side-effect is to set pstate->p_hasTargetSRFs true if appropriate. 2376 * 2377 * last_srf should be a copy of pstate->p_last_srf from just before we 2378 * started transforming the function's arguments. This allows detection 2379 * of whether the SRF's arguments contain any SRFs. 2380 */ 2381 void 2382 check_srf_call_placement(ParseState *pstate, Node *last_srf, int location) 2383 { 2384 const char *err; 2385 bool errkind; 2386 2387 /* 2388 * Check to see if the set-returning function is in an invalid place 2389 * within the query. Basically, we don't allow SRFs anywhere except in 2390 * the targetlist (which includes GROUP BY/ORDER BY expressions), VALUES, 2391 * and functions in FROM. 2392 * 2393 * For brevity we support two schemes for reporting an error here: set 2394 * "err" to a custom message, or set "errkind" true if the error context 2395 * is sufficiently identified by what ParseExprKindName will return, *and* 2396 * what it will return is just a SQL keyword. (Otherwise, use a custom 2397 * message to avoid creating translation problems.) 2398 */ 2399 err = NULL; 2400 errkind = false; 2401 switch (pstate->p_expr_kind) 2402 { 2403 case EXPR_KIND_NONE: 2404 Assert(false); /* can't happen */ 2405 break; 2406 case EXPR_KIND_OTHER: 2407 /* Accept SRF here; caller must throw error if wanted */ 2408 break; 2409 case EXPR_KIND_JOIN_ON: 2410 case EXPR_KIND_JOIN_USING: 2411 err = _("set-returning functions are not allowed in JOIN conditions"); 2412 break; 2413 case EXPR_KIND_FROM_SUBSELECT: 2414 /* can't get here, but just in case, throw an error */ 2415 errkind = true; 2416 break; 2417 case EXPR_KIND_FROM_FUNCTION: 2418 /* okay, but we don't allow nested SRFs here */ 2419 /* errmsg is chosen to match transformRangeFunction() */ 2420 /* errposition should point to the inner SRF */ 2421 if (pstate->p_last_srf != last_srf) 2422 ereport(ERROR, 2423 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 2424 errmsg("set-returning functions must appear at top level of FROM"), 2425 parser_errposition(pstate, 2426 exprLocation(pstate->p_last_srf)))); 2427 break; 2428 case EXPR_KIND_WHERE: 2429 errkind = true; 2430 break; 2431 case EXPR_KIND_POLICY: 2432 err = _("set-returning functions are not allowed in policy expressions"); 2433 break; 2434 case EXPR_KIND_HAVING: 2435 errkind = true; 2436 break; 2437 case EXPR_KIND_FILTER: 2438 errkind = true; 2439 break; 2440 case EXPR_KIND_WINDOW_PARTITION: 2441 case EXPR_KIND_WINDOW_ORDER: 2442 /* okay, these are effectively GROUP BY/ORDER BY */ 2443 pstate->p_hasTargetSRFs = true; 2444 break; 2445 case EXPR_KIND_WINDOW_FRAME_RANGE: 2446 case EXPR_KIND_WINDOW_FRAME_ROWS: 2447 case EXPR_KIND_WINDOW_FRAME_GROUPS: 2448 err = _("set-returning functions are not allowed in window definitions"); 2449 break; 2450 case EXPR_KIND_SELECT_TARGET: 2451 case EXPR_KIND_INSERT_TARGET: 2452 /* okay */ 2453 pstate->p_hasTargetSRFs = true; 2454 break; 2455 case EXPR_KIND_UPDATE_SOURCE: 2456 case EXPR_KIND_UPDATE_TARGET: 2457 /* disallowed because it would be ambiguous what to do */ 2458 errkind = true; 2459 break; 2460 case EXPR_KIND_GROUP_BY: 2461 case EXPR_KIND_ORDER_BY: 2462 /* okay */ 2463 pstate->p_hasTargetSRFs = true; 2464 break; 2465 case EXPR_KIND_DISTINCT_ON: 2466 /* okay */ 2467 pstate->p_hasTargetSRFs = true; 2468 break; 2469 case EXPR_KIND_LIMIT: 2470 case EXPR_KIND_OFFSET: 2471 errkind = true; 2472 break; 2473 case EXPR_KIND_RETURNING: 2474 errkind = true; 2475 break; 2476 case EXPR_KIND_VALUES: 2477 /* SRFs are presently not supported by nodeValuesscan.c */ 2478 errkind = true; 2479 break; 2480 case EXPR_KIND_VALUES_SINGLE: 2481 /* okay, since we process this like a SELECT tlist */ 2482 pstate->p_hasTargetSRFs = true; 2483 break; 2484 case EXPR_KIND_CHECK_CONSTRAINT: 2485 case EXPR_KIND_DOMAIN_CHECK: 2486 err = _("set-returning functions are not allowed in check constraints"); 2487 break; 2488 case EXPR_KIND_COLUMN_DEFAULT: 2489 case EXPR_KIND_FUNCTION_DEFAULT: 2490 err = _("set-returning functions are not allowed in DEFAULT expressions"); 2491 break; 2492 case EXPR_KIND_INDEX_EXPRESSION: 2493 err = _("set-returning functions are not allowed in index expressions"); 2494 break; 2495 case EXPR_KIND_INDEX_PREDICATE: 2496 err = _("set-returning functions are not allowed in index predicates"); 2497 break; 2498 case EXPR_KIND_ALTER_COL_TRANSFORM: 2499 err = _("set-returning functions are not allowed in transform expressions"); 2500 break; 2501 case EXPR_KIND_EXECUTE_PARAMETER: 2502 err = _("set-returning functions are not allowed in EXECUTE parameters"); 2503 break; 2504 case EXPR_KIND_TRIGGER_WHEN: 2505 err = _("set-returning functions are not allowed in trigger WHEN conditions"); 2506 break; 2507 case EXPR_KIND_PARTITION_BOUND: 2508 err = _("set-returning functions are not allowed in partition bound"); 2509 break; 2510 case EXPR_KIND_PARTITION_EXPRESSION: 2511 err = _("set-returning functions are not allowed in partition key expressions"); 2512 break; 2513 case EXPR_KIND_CALL_ARGUMENT: 2514 err = _("set-returning functions are not allowed in CALL arguments"); 2515 break; 2516 case EXPR_KIND_COPY_WHERE: 2517 err = _("set-returning functions are not allowed in COPY FROM WHERE conditions"); 2518 break; 2519 case EXPR_KIND_GENERATED_COLUMN: 2520 err = _("set-returning functions are not allowed in column generation expressions"); 2521 break; 2522 2523 /* 2524 * There is intentionally no default: case here, so that the 2525 * compiler will warn if we add a new ParseExprKind without 2526 * extending this switch. If we do see an unrecognized value at 2527 * runtime, the behavior will be the same as for EXPR_KIND_OTHER, 2528 * which is sane anyway. 2529 */ 2530 } 2531 if (err) 2532 ereport(ERROR, 2533 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 2534 errmsg_internal("%s", err), 2535 parser_errposition(pstate, location))); 2536 if (errkind) 2537 ereport(ERROR, 2538 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), 2539 /* translator: %s is name of a SQL construct, eg GROUP BY */ 2540 errmsg("set-returning functions are not allowed in %s", 2541 ParseExprKindName(pstate->p_expr_kind)), 2542 parser_errposition(pstate, location))); 2543 } 2544