Sub topic 10
Volatility, STRICT, and SECURITY DEFINER
This chapter assumes basic SQL, PostgreSQL data types, and the PL/pgSQL function structure from earlier chapters. You should also know how roles and permissions work in PostgreSQL.
Function attributes tell PostgreSQL how a function behaves. They affect query planning, handling of NULL, and the privileges used while the function runs. Choose them from the function’s actual behavior. An incorrect declaration can produce wrong results or create a security vulnerability.
Volatility categories
Volatility describes whether a function can change data or return different results during a statement.
| Attribute | Meaning | Typical use |
|---|---|---|
| `IMMUTABLE` | The same inputs always produce the same output | Arithmetic, text normalization |
| `STABLE` | The function does not modify data and is consistent within one statement | Reading tables or configuration |
| `VOLATILE` | The function may change data or return different results | `random()`, timestamps, writes |
VOLATILE is the default. Use the stricter category only when it is true.
An IMMUTABLE function can be evaluated during planning, used in an index, or replaced with a constant. Declaring a function immutable when it reads a table, checks the current time, or depends on a setting can make PostgreSQL reuse an invalid result.
A STABLE function may read database objects but must not modify them. It sees a consistent snapshot during a statement. A VOLATILE function can observe changes made by earlier operations in the same statement.
CREATE OR REPLACE FUNCTION normalize_email(p_email text)
RETURNS text
LANGUAGE sql
IMMUTABLE
STRICT
AS $$
SELECT lower(trim(p_email));
$$;
CREATE OR REPLACE FUNCTION random_discount()
RETURNS numeric
LANGUAGE sql
VOLATILE
AS $$
SELECT random();
$$;
SELECT normalize_email(' [email protected] ');
SELECT random_discount();`STRICT` and null inputs
STRICT is shorthand for RETURNS NULL ON NULL INPUT. PostgreSQL returns NULL without calling the function when any input argument is NULL.
This is useful when a missing input cannot produce a meaningful result. It also avoids running unnecessary code. Do not use STRICT when the function needs to interpret NULL as a meaningful value, such as “unknown,” “use the default,” or “match missing values.”
SECURITY DEFINER
By default, a function runs with the privileges of the caller. SECURITY DEFINER makes it run with the privileges of the function owner. This can expose carefully controlled operations, but it also creates a privilege-escalation risk.
A secure SECURITY DEFINER function should:
- Set a safe
search_path. - Schema-qualify tables and functions.
- Avoid trusting caller-controlled identifiers.
- Validate all inputs.
- Revoke unnecessary
PUBLICexecution privileges. - Grant execution only to the intended role.
session_user identifies the original connection user. current_user changes to the function owner inside a security-definer function.
CREATE SCHEMA IF NOT EXISTS app;
CREATE TABLE IF NOT EXISTS app.allowed_users (
username name PRIMARY KEY
);
CREATE OR REPLACE FUNCTION app.is_allowed()
RETURNS boolean
LANGUAGE sql
STABLE
SECURITY DEFINER
SET search_path = pg_catalog, app
AS $$
SELECT EXISTS (
SELECT 1
FROM app.allowed_users
WHERE username = session_user
);
$$;
REVOKE ALL ON FUNCTION app.is_allowed() FROM PUBLIC;The explicit search_path prevents an attacker from placing a malicious object earlier in the lookup path. The schema-qualified table reference adds another layer of protection.
Choosing attributes
Start with the least permissive truthful declaration:
- Use
IMMUTABLEonly for results independent of database contents, time, settings, and randomness. - Use
STABLEfor read-only functions whose result can vary between statements. - Keep
VOLATILEfor writes and changing values. - Add
STRICTwhen every null input must produce a null result. - Add
SECURITY DEFINERonly for a specific privilege boundary, then lock down its search path and permissions.
Exercise
A function reads a table and returns whether a customer is active. Which volatility and security settings are appropriate by default?
Show answer
Use STABLE if it only reads data. Use SECURITY DEFINER only if callers need controlled access they otherwise lack; otherwise keep the default invoker privileges.