Sub topic 2
Writing the body: dollar quoting and BEGIN ATOMIC
This chapter assumes you can run CREATE FUNCTION for a simple SQL function, and that you know what a schema and the search_path setting are. It covers the two ways to write a SQL function body and the practical differences between them.
Two ways to supply a body
PostgreSQL accepts a SQL function body in two forms:
- String body. The body is a string literal after
AS. It is stored as text and parsed again when the function is planned. This form works in every PostgreSQL version. - SQL-standard body. The body is written directly in the statement, either as
BEGIN ATOMIC ... ENDor as a singleRETURN expression. PostgreSQL parses it once at creation time and stores the parsed form. This form needs PostgreSQL 14 or later.
The rest of the chapter explains how to write each form and how they differ.
String bodies and dollar quoting
CREATE FUNCTION takes the body as a string constant. A plain single-quoted string works, but every single quote inside the body has to be doubled:
CREATE FUNCTION greeting(p_name text)
RETURNS text
LANGUAGE sql
AS 'SELECT ''Hello, '' || p_name || ''!''';This is hard to read and easy to get wrong. Dollar quoting avoids the problem. A dollar-quoted string starts with $tag$ and ends with the same $tag$. The tag can be empty, which gives the familiar $$. Nothing inside is treated as an escape, so quotes and backslashes are literal:
CREATE OR REPLACE FUNCTION greeting(p_name text)
RETURNS text
LANGUAGE sql
AS $$
SELECT 'Hello, ' || p_name || '!';
$$;
SELECT greeting('Ada');Rules for tags
- A tag follows the rules for an unquoted identifier, except that it cannot contain
$. Examples are$body$and$fn$. - Tags are case-sensitive.
$Body$does not close$body$. - The closing delimiter must match the opening one exactly.
Use a named tag when the body itself contains $$, for example when a function builds another function's definition. Give each nesting level a different tag:
CREATE FUNCTION make_noop_function_sql()
RETURNS text
LANGUAGE sql
AS $outer$
SELECT $inner$
CREATE FUNCTION noop() RETURNS void LANGUAGE sql AS $$ SELECT $$
$inner$;
$outer$;PostgreSQL ends the outer string at the first $outer$ it finds. The $$ and $inner$ sequences inside it are ordinary text.
Parameter references in a string body
Inside a string body you can refer to a parameter by name (p_name) or by position ($1, $2). Positional references are required for unnamed parameters. A name that matches a column in the query is ambiguous. The column wins, so prefix parameter names (p_) or qualify them with the function name (greeting.p_name).
When a string body is checked and resolved
For SQL functions, a string body is parsed and analyzed when you run CREATE FUNCTION, as long as the setting check_function_bodies is on (the default). Referencing a table that does not exist raises an error at creation. Tools such as pg_dump turn the setting off while restoring, so functions can be loaded before the tables they use.
That check does not freeze the meaning of the body. PostgreSQL keeps the text and resolves names again each time the function is planned, using the search_path in effect then. Two consequences follow:
- The function has no recorded dependency on the tables it reads. You can drop one of those tables, and the function stays in the catalog. It then fails when called.
- A different
search_pathin the caller's session can make the same text resolve to different objects.
CREATE TABLE rates (code text PRIMARY KEY, rate numeric NOT NULL);
CREATE FUNCTION rate_for_str(p_code text)
RETURNS numeric
LANGUAGE sql
STABLE
AS $$
SELECT rate FROM rates WHERE code = p_code;
$$;
DROP TABLE rates; -- succeeds
SELECT rate_for_str('VAT'); -- ERROR: relation "rates" does not existBEGIN ATOMIC bodies
With the SQL-standard form, the statements sit between BEGIN ATOMIC and END. Each statement ends with a semicolon, and so does the END:
CREATE TABLE rates (code text PRIMARY KEY, rate numeric NOT NULL);
CREATE FUNCTION rate_for(p_code text)
RETURNS numeric
LANGUAGE sql
STABLE
BEGIN ATOMIC
SELECT rate FROM rates WHERE code = p_code;
END;PostgreSQL parses the body at creation time and stores the parse tree. It resolves table, function and type names at that moment and records dependencies on them.
DROP TABLE rates;
-- ERROR: cannot drop table rates because other objects depend on it
-- DETAIL: function rate_for(text) depends on table ratesYou must drop the function first, or use DROP TABLE rates CASCADE. Changing a column the body uses gives a similar dependency error. The stored tree also does not depend on search_path at call time, which removes one source of surprises. This matters most for SECURITY DEFINER functions, covered in a later chapter.
For a function whose body is one expression, you can skip BEGIN ATOMIC and write RETURN:
CREATE FUNCTION add_vat(price numeric, rate numeric DEFAULT 0.20)
RETURNS numeric
LANGUAGE sql
IMMUTABLE
RETURN price * (1 + rate);Here the parameter names are the only way to reference arguments, because $1 is not available in the SQL-standard form.
Multiple statements and the result
A BEGIN ATOMIC body may contain several statements. As with string bodies, the result comes from the last statement. Earlier statements run for their side effects, in order:
CREATE TABLE audit_log (at timestamptz DEFAULT now(), note text);
CREATE FUNCTION log_and_count(p_note text)
RETURNS bigint
LANGUAGE sql
VOLATILE
BEGIN ATOMIC
INSERT INTO audit_log (note) VALUES (p_note);
SELECT count(*) FROM audit_log;
END;The word "atomic" here means the body runs as part of the calling statement's transaction, not that it opens a new one. If any statement fails, the whole call fails, and the caller's transaction decides what is rolled back.
Restrictions
- No polymorphic types. A
BEGIN ATOMICfunction cannot take or returnanyelement,anyarrayand similar types. Use a string body for those. - SQL only. The syntax exists only for
LANGUAGE sql. Functions in PL/pgSQL always take a string body. - Client splitting. A tool that splits a script on every semicolon will cut the function in half.
psqlunderstandsBEGIN ATOMICand handles it correctly. Check that your migration tool does the same. - Dump format.
pg_dumpoutputs aBEGIN ATOMICfunction in the same form, rebuilt from the stored tree. It does not needcheck_function_bodies = offfor ordering, because dependencies tell it the correct order.
Choosing between the forms
| Concern | String body (`AS $$ ... $$`) | `BEGIN ATOMIC` / `RETURN` |
|---|---|---|
| Minimum version | Any | PostgreSQL 14 |
| Parsed | At each plan, after a check at creation | Once, at creation |
| Dependencies on tables and functions | None recorded | Recorded, so `DROP` is blocked |
| Name resolution | Uses `search_path` at call time | Fixed at creation |
| Polymorphic types | Allowed | Not allowed |
| Positional `$1` references | Allowed | Not allowed |
| Other languages | Required | Not available |
A reasonable default on PostgreSQL 14 or later is the SQL-standard form for functions that read or write ordinary tables, because it catches broken drops early and does not depend on search_path. Use a string body for polymorphic functions, for code that must load on older versions, and for any language other than SQL.
Common errors
syntax error at or near "$". The opening and closing tags do not match, or a client has altered the text. Compare them character by character, including case.column reference "id" is ambiguous, or a parameter that seems to be ignored. A parameter name equals a column name. Rename the parameter or qualify it with the function name.syntax errorwhen you paste aBEGIN ATOMICfunction into a tool. The tool is splitting on semicolons. Run the file withpsql -f.SQL functions cannot accept polymorphic argumentsstyle errors withBEGIN ATOMIC. Switch that function to a string body.
Exercise
You create CREATE FUNCTION f() RETURNS int LANGUAGE sql BEGIN ATOMIC SELECT count(*) FROM t; END; and later run DROP TABLE t;. What happens, and what would have happened if f had been written with AS $$ SELECT count(*)::int FROM t; $$ instead?
Show answer
With BEGIN ATOMIC, the DROP TABLE fails with an error saying that function f() depends on table t, because the dependency was recorded when the function was created. (The body would also need a cast, count(*)::int, to match RETURNS int.) With the string body, no dependency exists, so DROP TABLE succeeds. The function remains, and calling it afterwards fails with relation "t" does not exist.
Exercise
Write a function shout(p_text text) that returns the text in upper case followed by an exclamation mark, as a string body that uses dollar quoting with the tag $fn$. Why would you choose a tag other than $$ here if the body contained the text $$?
Show answer
CREATE FUNCTION shout(ptext text) RETURNS text LANGUAGE sql IMMUTABLE AS $fn$ SELECT upper(ptext) || '!'; $fn$; A named tag is needed when the body contains $$, because the first $$ inside would otherwise be read as the end of the string. The unique tag $fn$ closes the string only at the matching $fn$.