Sub topic 11
Polymorphic functions
A polymorphic function accepts and returns more than one data type, so you write it once and call it with integers, text, dates or any other type. This chapter assumes you can write a basic SQL function with CREATE FUNCTION. You should also know how parameters and return types work, and how to reference parameters by name or as $1, $2.
Polymorphic pseudo-types
PostgreSQL provides placeholder types called pseudo-types. You can use them for function arguments and results, but not for table columns. Each placeholder is replaced by a real type when the function is called.
| Pseudo-type | Stands for |
|---|---|
| `anyelement` | Any data type |
| `anyarray` | An array of the type that `anyelement` resolves to |
| `anynonarray` | Any type that is not an array |
| `anyenum` | Any enum type |
| `anyrange`, `anymultirange` | A range or multirange type. The element type is the same one `anyelement` would resolve to. |
| `anycompatible` | Any type, with arguments promoted to a common type (PostgreSQL 13 and later) |
| `anycompatiblearray`, `anycompatiblenonarray`, `anycompatiblerange`, `anycompatiblemultirange` | The array, non-array, range and multirange forms of `anycompatible` |
Two families exist for historical reasons. The any... family is strict and the anycompatible... family is lenient. The sections below explain the difference.
A first polymorphic function
CREATE FUNCTION make_array(anyelement, anyelement)
RETURNS anyarray
LANGUAGE sql
IMMUTABLE
AS $$
SELECT ARRAY[$1, $2];
$$;
SELECT make_array(1, 2), make_array('a'::text, 'b'::text);The first call returns {1,2} as integer[]. The second returns {a,b} as text[]. PostgreSQL does not create two functions. It resolves the pseudo-types for each call and runs the same body.
How resolution works
At call time PostgreSQL looks at the actual argument types and applies these rules in order:
- Every argument declared
anyelementmust have the same actual type. - Every argument declared
anyarraymust be an array, and its element type must equal the type found foranyelement. - The result type is built from the resolved types. A result declared
anyarraybecomes an array of theanyelementtype.
The strict family fails on a mixed call:
SELECT make_array(1, 2.5);
-- ERROR: function make_array(integer, numeric) does not existThe anycompatible family handles the same call by choosing a common type, using the same rules as UNION or CASE:
CREATE FUNCTION make_array_c(anycompatible, anycompatible)
RETURNS anycompatiblearray
LANGUAGE sql
IMMUTABLE
AS $$
SELECT ARRAY[$1, $2];
$$;
SELECT make_array_c(1, 2.5);This returns {1,2.5} as numeric[]. Choose anycompatible when callers pass mixed numeric types or literals. Choose anyelement when you want callers to be exact.
Two rules apply across the whole signature:
- Separate groups do not interact. An
anyelementargument and ananycompatibleargument in the same function can resolve to different types. - If the result type is polymorphic, at least one argument must be polymorphic in the matching group. Otherwise
CREATE FUNCTIONfails with an error that it cannot determine the result data type. OUT parameters can supply the polymorphic input instead.
Using named parameters and arrays
Named parameters work with polymorphic types, and they usually read better than $1:
CREATE FUNCTION second_element(arr anyarray)
RETURNS anyelement
LANGUAGE sql
IMMUTABLE
AS $$
SELECT arr[2];
$$;
SELECT second_element(ARRAY[10, 20, 30]);
SELECT second_element(ARRAY['x', 'y']);The calls return 20 as integer and y as text. The anyarray argument pins down the element type, so the anyelement result needs no input of its own.
You can mix the two pseudo-types in one signature. They are linked, so the second argument must be of the array's element type:
CREATE FUNCTION first_or_default(arr anyarray, fallback anyelement)
RETURNS anyelement
LANGUAGE sql
IMMUTABLE
AS $$
SELECT COALESCE(arr[1], fallback);
$$;
SELECT first_or_default(ARRAY[]::int[], 0);
SELECT first_or_default(ARRAY[5, 6], 0);The first call returns 0 because the empty array has no first element. The second returns 5.
Polymorphic OUT parameters and sets
OUT parameters can be polymorphic. This lets one function return several columns whose types follow the input:
CREATE FUNCTION dup(f1 anyelement, OUT f2 anyelement, OUT f3 anyarray)
LANGUAGE sql
IMMUTABLE
AS $$
SELECT f1, ARRAY[f1, f1];
$$;
SELECT * FROM dup(22);
SELECT * FROM dup('xyz'::text);The first call returns 22 and {22,22}. The second returns xyz and {xyz,xyz}.
Set-returning functions can also be polymorphic:
CREATE FUNCTION first_n(arr anyarray, n int)
RETURNS SETOF anyelement
LANGUAGE sql
IMMUTABLE
AS $$
SELECT * FROM unnest(arr) LIMIT n;
$$;
SELECT * FROM first_n(ARRAY['a', 'b', 'c'], 2);Range types follow the same pattern. This function works for int4range, tstzrange and every other range type:
CREATE FUNCTION range_start(r anyrange)
RETURNS anyelement
LANGUAGE sql
IMMUTABLE
AS $$
SELECT lower(r);
$$;
SELECT range_start(int4range(3, 9));This returns 3.
Limits of the function body
The body of a SQL function is checked when the function is created. With polymorphic arguments, the checker sees the pseudo-types, not the types a caller will use. Operators that are defined only for concrete types therefore fail at creation:
CREATE FUNCTION bad_add(a anyelement, b anyelement)
RETURNS anyelement
LANGUAGE sql
AS $$ SELECT a + b; $$;
-- ERROR: operator does not exist: anyelement + anyelementYou can only call functions and operators that are themselves declared on polymorphic types. Examples are array subscripting, ARRAY[...], unnest, lower and upper on ranges, and COALESCE. If you need arithmetic, you have three choices:
- Write one overload per concrete type.
- Use
anycompatiblewith a function that accepts it. For example,greatest(a, b)works on any comparable type. - Move to PL/pgSQL, where the body is resolved at run time and
formatplusEXECUTEcan build statements per type.
Other points to know:
- Polymorphic arguments may not work together with a
BEGIN ATOMICbody. Some PostgreSQL versions reject that combination with an error that an unquoted function body cannot have polymorphic arguments. Use a dollar-quoted body for polymorphic functions, as in every example above. - Bare string literals have the type
unknown. If every polymorphic argument is anunknownliteral or an untypedNULL, resolution can fail with a message that it could not determine the polymorphic type. Add a cast, such as'a'::text. - A
NULLnext to a typed argument is fine.make_array(1, NULL)returns{1,NULL}. STRICTworks as usual. A strict polymorphic function returnsNULLwithout running if any argument isNULL.- Overloads interact with polymorphic functions. When a concrete function and a polymorphic function both match, PostgreSQL prefers the one whose declared types fit the call more exactly. You can add a specialized overload for one type, for example for speed, and keep the polymorphic one as the general case.
Exercises
Exercise
Write a function last_element that takes any array and returns its last element, with a result type matching the array's element type. Show a call with a text array.
Show answer
CREATE FUNCTION lastelement(arr anyarray) RETURNS anyelement LANGUAGE sql IMMUTABLE AS $$ SELECT arr[arrayupper(arr, 1)]; $$; SELECT last_element(ARRAY['a', 'b', 'c']); The call returns c. The anyarray argument fixes the element type, so the anyelement result needs no separate input.
Exercise
Why does make_array(1, 2.5) fail when the function is declared with anyelement, and what change to the declaration makes it succeed?
Show answer
With anyelement, every matching argument must have exactly the same type. The literal 1 is integer and 2.5 is numeric, so no function matches and PostgreSQL reports that the function does not exist. Declaring the parameters as anycompatible and the result as anycompatiblearray lets PostgreSQL pick a common type (numeric) and cast the arguments, so the call returns {1,2.5} as numeric[].