Sub topic 10
Replacing, overloading and dropping functions
This chapter covers how PostgreSQL identifies a function, what CREATE OR REPLACE FUNCTION may and may not change, how overloads are chosen at call time, and how to remove functions safely. It assumes you can write a basic SQL function (the first chapters of this tutorial), know what a schema and a role are, and can run statements in psql.
A function is identified by its input types
A function's identity is its schema, its name, and the list of its input argument types. Parameter names, defaults, the return type and the body are not part of the identity. This explains most of the rules below.
The catalog shows each function's full signature. Cast the oid to regprocedure:
SELECT oid::regprocedure
FROM pg_proc
WHERE proname = 'add_tax';With the add_tax function from the first chapter, this returns add_tax(numeric,numeric). In psql, \df add_tax gives a similar listing.
OUT parameters are not part of a function's identity. Two functions that differ only in their OUT columns are the same function, so the second CREATE fails.
Replacing a function
CREATE OR REPLACE FUNCTION finds the existing function with the same schema, name and input types, then swaps in the new definition:
CREATE OR REPLACE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.20)
RETURNS numeric
LANGUAGE sql
IMMUTABLE
AS $$
SELECT round(price * (1 + rate), 2);
$$;The replacement keeps the function's object ID, owner and privileges. Views, triggers and other functions that refer to it keep working, and nobody has to re-grant EXECUTE.
If the signature differs, you do not replace anything. You create a second function with the same name. Add a third parameter and the old two-parameter version stays in place. This surprises people who expected an upgrade.
What replacement refuses to change
| Change | Result |
|---|---|
| Body, volatility, `STRICT`, `COST`, `SET` options | Allowed |
| Default value of an existing parameter | Allowed |
| Return type | Error: `cannot change return type of existing function` |
| Type or number of OUT columns | Error, same as the return type |
| Name of an input parameter | Error: `cannot change name of input parameter` |
| Removing a default from a parameter | Error: `cannot remove parameter defaults from existing function` |
| Input argument types | Creates a new overload instead |
Each error includes a hint to use DROP FUNCTION first. For example:
CREATE OR REPLACE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.20)
RETURNS double precision
LANGUAGE sql
IMMUTABLE
AS $$
SELECT (price * (1 + rate))::double precision;
$$;
-- ERROR: cannot change return type of existing function
-- HINT: Use DROP FUNCTION add_tax(numeric,numeric) first.Changing what replacement cannot
Drop and recreate the function inside one transaction. DDL in PostgreSQL is transactional, so other sessions never see the function missing:
BEGIN;
DROP FUNCTION add_tax(numeric, numeric);
CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.20)
RETURNS double precision
LANGUAGE sql
IMMUTABLE
AS $$
SELECT (price * (1 + rate))::double precision;
$$;
GRANT EXECUTE ON FUNCTION add_tax(numeric, numeric) TO app_user;
COMMIT;The new function is a different object. It has a new owner (you), and the default PUBLIC execute privilege is back. Re-apply every GRANT and REVOKE yourself. For a SECURITY DEFINER function, forgetting the REVOKE ... FROM PUBLIC leaves it callable by everyone.
Overloading
Several functions may share a name if their input types differ:
CREATE FUNCTION label(v integer) RETURNS text
LANGUAGE sql IMMUTABLE
AS $$ SELECT 'int:' || v::text; $$;
CREATE FUNCTION label(v numeric) RETURNS text
LANGUAGE sql IMMUTABLE
AS $$ SELECT 'num:' || v::text; $$;
CREATE FUNCTION label(v text) RETURNS text
LANGUAGE sql IMMUTABLE
AS $$ SELECT 'text:' || v; $$;
SELECT label(1), -- int:1
label(1.5), -- num:1.5
label(1::bigint), -- num:1
label('x'::text), -- text:x
label('5'); -- text:5At parse time, PostgreSQL chooses the function using the types of the call's arguments. It does not look at the values or at the return type. The rules, simplified:
- Candidates are the functions with that name and a compatible argument count, found through the
search_path. - Candidates with the most exactly matching argument types are kept.
- Otherwise, implicit casts are allowed.
biginttonumericis implicit, solabel(1::bigint)calls the numeric version.biginttointegeris only an assignment cast, so it is not considered. - An untyped literal such as
'5'is of typeunknown. If candidates disagree, PostgreSQL prefers the one that takes a string type. That is whylabel('5')returnstext:5and notint:5.
Ambiguous calls
When two candidates need the same amount of casting, the call fails:
CREATE FUNCTION pair(a integer, b numeric) RETURNS text
LANGUAGE sql IMMUTABLE AS $$ SELECT 'int,num'; $$;
CREATE FUNCTION pair(a numeric, b integer) RETURNS text
LANGUAGE sql IMMUTABLE AS $$ SELECT 'num,int'; $$;
SELECT pair(1, 1);
-- ERROR: function pair(integer, integer) is not unique
-- HINT: Could not choose a best candidate function. You might need to add explicit type casts.
SELECT pair(1, 1::numeric); -- int,numAdding a parameter with a default as a new overload can create the same kind of ambiguity. Calls that used to resolve cleanly may start failing with is not unique. Before you add an overload, ask whether replacing the old function and adding a default would be simpler.
Overloads and schemas
The same name and types in different schemas are different functions. If an unqualified call could match several of them, PostgreSQL prefers the one in the schema that appears earlier in search_path. Qualify the name (billing.add_tax(...)) when it matters.
A function and a procedure cannot share the same name and input types in one schema.
Altering a function without touching its body
ALTER FUNCTION changes attributes and placement. It cannot change the body, parameters or return type.
ALTER FUNCTION add_tax(numeric, numeric) RENAME TO add_vat;
ALTER FUNCTION add_vat(numeric, numeric) OWNER TO billing_owner;
ALTER FUNCTION add_vat(numeric, numeric) PARALLEL SAFE;
ALTER FUNCTION add_vat(numeric, numeric) SET search_path = pg_catalog, public;You can also use SET SCHEMA, STABLE/IMMUTABLE/VOLATILE, STRICT, COST, ROWS and SECURITY DEFINER. Renaming keeps the grants and the object ID. Callers that use the old name break, so rename in the same transaction as a compatibility wrapper if you need a transition period.
Dropping functions
DROP FUNCTION needs the input argument types, because the name alone may match several overloads:
DROP FUNCTION IF EXISTS label(text);
DROP FUNCTION label(integer), label(numeric);You may leave out the argument list only when exactly one function with that name exists in the schema:
DROP FUNCTION add_vat;If two or more match, PostgreSQL reports that the function name is not unique, and nothing is dropped. This protects you from removing the wrong overload. Procedures need DROP PROCEDURE, and using DROP FUNCTION on one is an error.
Dependencies
DROP refuses to run if another object depends on the function, such as a view, a column default, a trigger or an index expression. It lists the dependents. DROP ... CASCADE removes them as well, so read the list before you add CASCADE.
Dependencies on the function's body depend on how you wrote it:
- A
BEGIN ATOMICbody is parsed at creation, and PostgreSQL records which tables and functions it uses. Dropping a table that the body references is blocked. - A string body (
AS $$ ... $$) is stored as text and is not tracked. Dropping a table that it references succeeds, and the function fails the next time it runs.
Exercise
You have CREATE FUNCTION area(w numeric, h numeric) RETURNS numeric .... You run CREATE OR REPLACE FUNCTION area(w numeric, h numeric, d numeric DEFAULT 1) RETURNS numeric .... How many area functions exist afterwards, and what is the risk?
Show answer
Two. The input types differ, so the second statement created an overload and did not replace the original. The old two-argument version is still there, and a call like area(2, 3) can now match both candidates and fail as ambiguous or pick an unexpected one. Drop the old function, or write the replacement with the original signature.
Exercise
A function get_total(order_id int) RETURNS numeric is used in a view and has GRANT EXECUTE for app_user. You need it to return numeric plus a currency code through OUT columns. Describe the safest way to make the change.
Show answer
CREATE OR REPLACE cannot change the return type or OUT columns, and DROP FUNCTION fails while the view depends on it. Either add a new function with a different name and migrate callers, or in one transaction drop the view, drop the function, create the new function, recreate the view, and restore the GRANT for app_user. Avoid DROP ... CASCADE unless you have read which objects it removes.