CREATE FUNCTION
Creates a scalar SQL-language function:
CREATE [OR REPLACE] FUNCTION name(argument type [, ...])
RETURNS type
[LANGUAGE SQL]
[SECURITY INVOKER]
AS $$ SELECT expression $$;
For LANGUAGE SQL, the body must contain exactly one SELECT returning one column of the declared type. Argument names can be used in
the body; $1, $2, and subsequent parameters are also supported.
SECURITY INVOKER is the default and may be declared explicitly. SECURITY DEFINER is
executed with the function owner as current_user, while preserving session_user. Function
dependencies in the body are checked recursively under that context. The SELECT may read
relations and must return at most one row; zero rows return NULL.
CREATE FUNCTION add_one(value int)
RETURNS int
AS $$ SELECT value + 1 $$;
SELECT add_one(41); -- 42
Small scalar functions can also use LANGUAGE plamphi after
CREATE EXTENSION plamphi:
CREATE FUNCTION double_value(value int4)
RETURNS int4
LANGUAGE plamphi
AS $$ value * 2 $$;
SELECT double_value(21); -- 42
PLAmphi functions can also iterate over text and compute rules directly in the
language body. Text indices start at zero, .length counts Unicode characters,
and indexing outside the text raises an error:
CREATE FUNCTION second_character(value text)
RETURNS text
LANGUAGE plamphi
AS $$
value[1]
$$;
SELECT second_character('Amphi'); -- m
With these operations, a CPF or CNPJ validator can calculate check digits
using PLAmphi loops and arithmetic; the formula does not need a SELECT.
The same control flow can validate and update inventory inside the caller’s
transaction. A guarded UPDATE ... RETURNING prevents concurrent withdrawals
from driving the balance below zero; throw raises SQLSTATE P0001.
The PLAmphi body can end with an expression of the declared return type or
explicitly return on every possible path; paths that can fall through without a
value are rejected. In this slice, parameters and return values must be
bool, int2, int4, int8,
numeric, float8, or text. Scalar control flow and sql<T> templates with
SELECT without row locks or INSERT, UPDATE, and DELETE with RETURNING
are supported; scalar templates return one column, while for (const row of sql<T[]>...) iterates typed table records. Zero rows in a nullable scalar result
return NULL; more than one row in a scalar result raises an error and rolls
back the calling statement. SQL uses the caller’s transaction, snapshot, and
identity. Read-only templates reject calls to SQL VOLATILE functions; writes
commit or roll back with the caller. A try/catch block containing DML opens a
real savepoint: when a write fails, the protected block is rolled back and the
calling transaction remains usable. The caught Error exposes sqlstate,
message, retryable, and cause; rethrow errors the function does not intend
to handle. The transfer_stock E2E demonstrates two atomic updates: a failure
when crediting the target also rolls back the debit from the source. print,
cursors in DO, explicit transaction blocks, afterCommit, and SECURITY DEFINER
remain unavailable. Persistent functions can iterate typed records from a query:
CREATE TABLE stock_by_product (
product_id int4 PRIMARY KEY,
quantity int4 NOT NULL CHECK (quantity >= 0)
);
CREATE TABLE order_items (
item_id int4 PRIMARY KEY,
order_id int4 NOT NULL,
product_id int4 NOT NULL,
quantity int4 NOT NULL CHECK (quantity > 0),
unit_price int4 NOT NULL CHECK (unit_price >= 0)
);
CREATE FUNCTION process_order(order_id int4)
RETURNS int4 LANGUAGE plamphi AS $$
let total = 0;
let item_count = 0;
for (const item of sql<order_items[]>`
SELECT * FROM order_items
WHERE order_id = ${order_id}
ORDER BY item_id
`) {
const updated_stock = sql<int4?>`
UPDATE stock_by_product
SET quantity = quantity - ${item.quantity}
WHERE product_id = ${item.product_id}
AND quantity >= ${item.quantity}
RETURNING quantity
`;
if (updated_stock == null) {
throw 'Missing product stock or insufficient quantity';
} else {
total = total + item.quantity * item.unit_price;
item_count = item_count + 1;
}
}
if (item_count == 0) {
throw 'Order has no items';
} else {
return total;
}
$$;
Each item is a typed record. A failure on a later item rolls back earlier
stock updates, and an outer ROLLBACK also undoes the order. The current host
buffers query rows in memory before iteration. DML row conflicts may return 40001.
The DDL and function history persist; the function is recompiled when the
database is reopened.
A function can also send an event to a queue. Sending uses the same transaction as the stock changes: commit publishes the event, while rollback discards both the event and the changes. Structured values are sent as JSON; text is passed through unchanged:
CREATE QUEUE order_events (payload text);
CREATE FUNCTION process_and_notify(order_id int4, total int4)
RETURNS int4 LANGUAGE plamphi AS $$
db.order_events.send({ order_id: order_id, total: total });
return total;
$$;
If a send occurs in a try block that fails, the block savepoint discards that
provisional message too. The queue is resolved and validated at compile time;
its persisted OID identifies the resource at runtime.
The same pattern can combine a conditional update with an audit row. The
balance = old_balance condition detects a concurrent change after the read;
the function fails instead of writing a value calculated from stale data:
CREATE TABLE account_balance (
account_id int4 PRIMARY KEY,
balance int4 NOT NULL CHECK (balance >= 0)
);
CREATE TABLE balance_audit (
account_id int4 NOT NULL,
old_balance int4 NOT NULL,
new_balance int4 NOT NULL
);
CREATE QUEUE balance_events (payload text);
CREATE FUNCTION change_balance(account_id int4, delta int4)
RETURNS int4 LANGUAGE plamphi AS $$
const old_balance = sql<int4?>`
SELECT balance FROM account_balance WHERE account_id = ${account_id}
`;
if (old_balance == null) {
throw 'Account not found';
} else {
const new_balance = old_balance + delta;
if (new_balance < 0) {
throw 'Insufficient balance';
} else {
const updated = sql<int4?>`
UPDATE account_balance SET balance = ${new_balance}
WHERE account_id = ${account_id} AND balance = ${old_balance}
RETURNING balance
`;
if (updated == null) {
throw 'Balance changed concurrently';
} else {
sql<int4>`INSERT INTO balance_audit
(account_id, old_balance, new_balance)
VALUES (${account_id}, ${old_balance}, ${updated})
RETURNING account_id`;
db.balance_events.send({ account_id: account_id,
old_balance: old_balance, new_balance: updated });
return updated;
}
}
}
$$;
The balance, audit row, and event belong to the same transaction. A missing account, insufficient balance, concurrent change, or outer rollback leaves no partial effects.
PLAmphi DO blocks, functions, and procedures can also contain direct SQL.
SELECT ... INTO and DML with RETURNING ... INTO bind local variables as SQL
parameters. The target must be nullable: zero rows assign null and set FOUND
to false; one row assigns the value and sets FOUND to true; multiple rows
raise 21000 without a partial assignment. ROW_COUNT is 0 or 1 in these
cases, and FOUND equals ROW_COUNT > 0. For DML without RETURNING,
ROW_COUNT is the actual number of affected rows and FOUND reports whether
any row changed. This stage accepts one scalar target. A failed command keeps
the previous status values.
CREATE FUNCTION update_stock(product int4, amount int4) RETURNS int4
LANGUAGE plamphi AS $$
let remaining: int4? = null;
UPDATE stock SET quantity = quantity - amount
WHERE product_id = product
RETURNING quantity INTO remaining;
return remaining ?? 0;
$$;
The body accepts dollar-quoted strings, including named delimiters ($$ ... $$ and
$SQL$ ... $SQL$). OR REPLACE keeps the function identity and creates a new revision.
Different argument lists are distinct overloads.
History and diff
Every create or replace stores the complete DDL in sys.object_revision, together with its
version, author, and timestamp:
SELECT version, source, created_by, created_at
FROM sys.object_revision
WHERE object_kind = 'function'
ORDER BY object_oid, version;
The retained history is controlled by amphi.function_history_retention. The default is 10;
a positive value keeps the latest N versions and 0 keeps all versions:
SET amphi.function_history_retention = 20;
The diff returns one text cell in unified-diff format, with one complete source line per diff
line. The signature must identify the exact overload; a version can be a number or HEAD:
SELECT sys.function_diff('add_one(int)', '1', 'HEAD');
The body also records the functions it calls. While an active dependent function exists,
DROP FUNCTION fails with 2BP01; remove or replace the dependent first.
The function owner is the user who created the first revision. Only that owner or an admin may
use CREATE OR REPLACE FUNCTION or DROP FUNCTION.
Current limitations: scalar SQL functions follow the one-SELECT contract; persistent PLAmphi
functions are limited to the scalar subset above. Persisted procedures are documented in CREATE PROCEDURE; packages and selective version restoration are outside this delivery. DROP FUNCTION removes
the active definition but preserves retained history. Recreating the same signature after a drop
creates a new object with a new OID and history starting at version 1; the previous history
remains attached to the old OID.
Trigger functions
A PLAmphi trigger function declares RETURNS trigger and is attached to a table with
CREATE TRIGGER. The first slice supports BEFORE ROW triggers for INSERT and UPDATE on heap
tables:
CREATE FUNCTION validate_quantity()
RETURNS trigger
LANGUAGE plamphi AS $$
if (NEW.quantity < 0) {
throw 'Invalid quantity';
}
return NEW;
$$;
CREATE TRIGGER validate_quantity
BEFORE INSERT OR UPDATE ON inventory
FOR EACH ROW
EXECUTE FUNCTION validate_quantity();
NEW is the proposed row. OLD is available during UPDATE. Return NEW to continue;
return null suppresses the row. throw aborts the statement and rolls back its writes.
Trigger functions cannot be called through SELECT. Embedded SQL and transaction control are not
available in a trigger body; DELETE, AFTER, statement-level triggers, and other relation kinds
are not supported yet.