Re: Argument casting hierarchy?

From: Andrew Gierth <andrew(at)tao11(dot)riddles(dot)org(dot)uk>
To: Wells Oliver <wells(dot)oliver(at)gmail(dot)com>
Cc: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Argument casting hierarchy?
Date: 2019-07-02 03:26:40
Message-ID: 8736jpqgne.fsf@news-spur.riddles.org.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

>>>>> "Wells" == Wells Oliver <wells(dot)oliver(at)gmail(dot)com> writes:

Wells> Hi guys, hoping you can help clarify what the 'hierarchy' of
Wells> casts might be in function arguments.

In terms of which casts will be selected in some given context, there
isn't exactly a "hierarchy", but some types are designated as
"preferred" types in their category. Of the builtin types, the preferred
ones are boolean, text, oid, double precision, inet, timestamptz,
interval and varbit. (See pg_type.typispreferred and
pg_type.typcategory.)

If there are several ways to implicitly cast function arguments to match
signatures of known functions, then the result is ambiguous (and hence
an error) _unless_ there is one (and only one) combination of casts to
preferred types in matching categories. So in your example, if you had a
variant of the function (a float8, b float8) then smallint inputs would
call that variant, in preference to the bigint or real ones, because
float8 (aka double precision) is a preferred type in category N (number
types).

You have to be a bit careful with this because it sometimes leads to
unexpected casts or loss of precision. If your function will be casting
the input values to "numeric", for example, then it is better to have
just one function with numeric type args, rather than risk getting casts
like numeric -> float8 -> numeric. Another commonly seen example is the
mis-casting of "date" type to timestamptz (as the preferred type) where
timestamp without tz was intended or semantically required.

--
Andrew (irc:RhodiumToad)

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Prakash Ramakrishnan 2019-07-02 05:51:52 restore error
Previous Message Tom Lane 2019-07-01 23:41:06 Re: Statistics tables not being updated anymore