Sub topic 10
Volatility, STRICT, and SECURITY DEFINER
This chapter covers three attributes that change how PostgreSQL plans, calls, and authorizes your functions. It assumes you can write a PL/pgSQL function with parameters and a return type, and that you know roles, GRANT, and search_path at a basic level. The attributes sit between the signature and the body, so you can set them without touching the logic.
Where attributes go
Attributes come after RETURNS and before AS. Order among them does not matter.
CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.2)
RETURNS numeric
LANGUAGE plpgsql
IMMUTABLE
STRICT
AS $$
BEGIN
RETURN round(price * (1 + rate), 2);
END;
$$;You can change them later without rewriting the body:
ALTER FUNCTION add_tax(numeric, numeric) VOLATILE;To see what a function currently declares, read the catalog. provolatile holds i, s, or v, proisstrict is true for STRICT, and prosecdef is true for SECURITY DEFINER.
SELECT proname, provolatile, proisstrict, prosecdef
FROM pg_proc
WHERE proname IN ('add_tax', 'get_customer_email');Volatility
Volatility is a promise you make to the planner about what the function does. It is not checked against the body. There are three levels.
| Level | Promise | Typical use |
|---|---|---|
| `VOLATILE` (default) | May change the database or return a different result on each call, even within one statement | Anything that writes, or calls `random()` or `clock_timestamp()` |
| `STABLE` | Does not modify the database. Same arguments give the same result within one statement | Lookups such as `get_customer_email` and `orders_over` |
| `IMMUTABLE` | Does not modify the database and does not read it. Same arguments give the same result forever | Pure computation such as `add_tax` |
What the planner does with the promise
- A
VOLATILEfunction is called once for every row where it appears. The planner cannot use it in an index scan condition. - A
STABLEfunction can be used in an index scan condition, because its value is fixed for the whole statement. - An
IMMUTABLEfunction called with constant arguments can be evaluated once at plan time. OnlyIMMUTABLEfunctions are allowed in index expressions and in generated columns.
CREATE FUNCTION normalize_email(p_email text)
RETURNS text
LANGUAGE sql
IMMUTABLE
STRICT
AS $$
SELECT lower(btrim(p_email));
$$;
CREATE INDEX customers_email_norm_idx
ON customers (normalize_email(email));A query with WHERE normalize_email(email) = '[email protected]' can now use that index.
Gotchas
- Lying about
IMMUTABLEcorrupts indexes. Suppose anIMMUTABLEfunction reads atax_ratestable. When the table changes, the function's answers change, but the index entries built from the old answers stay. Queries then return wrong rows. This is a silent failure with no error message. Mark a functionIMMUTABLEonly if it depends solely on its arguments. - Settings count as inputs. A function that depends on
TimeZone,search_path, or locale is at mostSTABLE. Formatting atimestamptzas text is an example. - Non-volatile functions cannot write. A
STABLEPL/pgSQL function that runsINSERTfails with an error such asINSERT is not allowed in a non-volatile function. - Snapshots differ. A
STABLEfunction sees the snapshot of the statement that called it. AVOLATILEfunction inREAD COMMITTEDmode takes a fresh snapshot for each statement inside it. So it can see rows committed by other sessions while the outer query is still running. - Being too cautious costs performance. If a pure function stays
VOLATILE, you lose index use and constant folding. Declare the strongest level that is true.
STRICT and NULL handling
By default a function is CALLED ON NULL INPUT. PostgreSQL runs the body even when an argument is NULL, and your code decides what that means. With STRICT, also written RETURNS NULL ON NULL INPUT, PostgreSQL skips the call and returns NULL if any argument is NULL.
CREATE FUNCTION full_name(p_first text, p_last text)
RETURNS text
LANGUAGE plpgsql
IMMUTABLE
STRICT
AS $$
BEGIN
RETURN p_first || ' ' || p_last;
END;
$$;
SELECT full_name('Ada', 'Lovelace'); -- Ada Lovelace
SELECT full_name('Ada', NULL) IS NULL; -- true, body never ranWithout STRICT, the concatenation would still yield NULL here, but the body would run. For a function with side effects or a RAISE, that difference matters.
Points to keep in mind:
- One
NULLis enough. With three arguments, aNULLin any one of them short-circuits the whole call. - Do not use
STRICTwhenNULLis meaningful. A function that returns a default for missing input must stayCALLED ON NULL INPUTand handleNULLexplicitly, for example withcoalesce. STRICTcan help the planner. A strict, simple SQL function can be inlined and can let the planner reason aboutNULLresults. It is also a cheap way to document intent.- Defaults do not rescue
NULL. A default such asrate numeric DEFAULT 0.2applies only when the argument is omitted. PassingNULLexplicitly still triggers theSTRICTshortcut. - Strictness is separate from
SELECT INTO STRICT. That is a statement-level check for exactly one row, covered in the error handling chapter.
SECURITY DEFINER
Normally a function is SECURITY INVOKER. It runs with the privileges of the role that calls it. SECURITY DEFINER runs it with the privileges of the role that owns it. This lets you expose a narrow operation without granting access to the underlying table.
CREATE FUNCTION customer_order_count(p_id integer)
RETURNS bigint
LANGUAGE sql
STABLE
SECURITY DEFINER
SET search_path = pg_catalog, pg_temp
AS $$
SELECT count(*) FROM public.orders WHERE customer_id = p_id;
$$;
REVOKE ALL ON FUNCTION customer_order_count(integer) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION customer_order_count(integer) TO app_reader;Here app_reader can call the function but cannot SELECT from orders. This example assumes the role app_reader exists and that the function's owner can read public.orders.
The three required habits
- Pin
search_path. Without aSET search_pathclause, the function uses the caller's setting. A caller who can create objects in a schema on the path could place a function or table with the same name earlier in the path. The definer function would then run the attacker's code with the owner's privileges. Listpg_catalogfirst, putpg_templast, and schema-qualify your own objects as the example does. - Revoke
EXECUTEfromPUBLIC. PostgreSQL grantsEXECUTEon new functions to everyone by default. Revoke it, then grant it only to the roles that need it. - Use a low-privilege owner. The function has all the privileges of its owner. If a superuser owns it, a bug in the function is a superuser bug. Create a dedicated role that owns only what the function needs.
Behavior inside a definer function
current_userreturns the owner.session_userstill returns the login role, so use it for audit logging.- Row-level security applies to the owner. Table owners bypass it unless the table uses
FORCE ROW LEVEL SECURITY. A definer function owned by a table owner can therefore read rows the caller could not see. - Validate arguments as untrusted input. If you build queries dynamically, use
format()with%IandUSINGas described in the dynamic SQL chapter.
Combining attributes
The attributes are independent, so you can mix them. A trigger function that stamps an audit table the user cannot write to might be VOLATILE SECURITY DEFINER SET search_path = pg_catalog, pg_temp. A pure helper is IMMUTABLE STRICT. A read-only lookup that crosses a privilege boundary is STABLE SECURITY DEFINER.
Adding SET search_path to a SQL function has a side effect. PostgreSQL cannot inline a function that has a SET clause into the calling query, so it is called as a black box. For a hot, tiny function, measure before you add it. For a SECURITY DEFINER function, security wins.
Exercise
A function slug(p_title text) lowercases the title and replaces spaces with hyphens, using only built-in string functions. You want to index slug(title) on an articles table, and NULL titles should give NULL without running the body. Which attributes do you declare?
Show answer
Declare IMMUTABLE and STRICT. The function reads no tables and no settings, so IMMUTABLE is true and is required for an index expression. STRICT returns NULL for a NULL title without running the body. The function needs no SECURITY DEFINER.
Exercise
You wrote a SECURITY DEFINER function that lets a reporting role count rows in a table it cannot read. Name three settings or statements you must add so the function is safe.
Show answer
Add SET search_path = pg_catalog, pg_temp (and schema-qualify table names) so callers cannot hijack name resolution. Run REVOKE ALL ON FUNCTION ... FROM PUBLIC to remove the default EXECUTE grant. Then run GRANT EXECUTE ON FUNCTION ... TO the reporting role. The function should also be owned by a role with only the privileges it needs.