-2

Currently getting an error about type casts,

HINT: Could not choose a best candidate function. You might need to add explicit type casts.

Let's say I create an overloaded function foo

CREATE FUNCTION foo(x int)
RETURNS int AS $$
  SELECT 1
$$ LANGUAGE sql;

CREATE FUNCTION foo(x interval)
RETURNS int AS $$
  SELECT 2
$$ LANGUAGE sql;

How come when I then call that function,

SELECT foo('5 days');

I get,

ERROR:  function foo(unknown) is not unique
LINE 1: SELECT foo('5 days');
               ^
HINT:  Could not choose a best candidate function. You might need to add explicit type casts.

Question inspired by looking into generate_series and the conversations on irc.freenode.net/#postgresql

Evan Carroll
  • 63,051
  • 46
  • 242
  • 479

1 Answers1

1

The reason for this is because '5 days' at that point is essentially '5 days'::unknown. From there the question is whether the right option is

  • '5 days'::int or
  • '5 days'::interval

Sure, '5 days'::int isn't valid, but unknown -> int is required so you can say SELECT '5' + 5;. PostgreSQL doesn't know that "5 days" will throw an exception until after it tries and because both are typed the same it just gives up rather than guessing randomly.

There is no good work around to this.

You can see it documented under Functions: Type Conversion

Evan Carroll
  • 63,051
  • 46
  • 242
  • 479
  • 2
    Or use the SQL standard notation interval '5' day –  Nov 10 '17 at 06:49
  • how do you know everything? that's a literal syntax for interval? And, more over why isn't that the syntax then in the docs for generate_series – Evan Carroll Nov 10 '17 at 07:27
  • Because it's documented in the manual: https://www.postgresql.org/docs/10/static/datatype-datetime.html#DATATYPE-INTERVAL-INPUT It's a bit hard to read but there is an example: INTERVAL '1' YEAR and thtat is the same syntax that Oracle uses –  Nov 10 '17 at 07:29
  • Right, I'm just wondering why any other syntax is used anywhere else, it would seem we should be relegating the current string syntax to the foot notes of that doc, and not vise-versa. Though I would make the same argument about LIMIT/OFFSET – Evan Carroll Nov 10 '17 at 07:31
  • @a_horse_with_no_name is there a literal method for 1 Year 1 Month, or do I have to add the interval literals for one year, and one month? – Evan Carroll Nov 10 '17 at 07:37
  • 1
    interval '1-2' year to month or simply interval '1-2' see: https://www.postgresql.org/docs/10/static/datatype-datetime.html#DATATYPE-INTERVAL-INPUT-EXAMPLES –  Nov 10 '17 at 07:49
  • @a_horse_with_no_name that's really cool, of course that doesn't solve the problem here which is backwards compat with those functions using the unknown->interval thing, but in the future I'll personally always use the standardized version. – Evan Carroll Nov 10 '17 at 08:08