Packages

A PostgREST and Supabase-compatible REST API powered by Elixir and Ecto.

Current section

Files

Jump to
pgrest docs guides rpc.md
Raw

docs/guides/rpc.md

# Functions and RPC

`/rpc/name` calls a registered database function. GET and HEAD bind query-string
arguments and run read-only; POST binds a JSON object's named arguments. Volatile
functions that write fail with `25006` on GET. Resource returns support filters,
embeds, counts, JSON, singular JSON and CSV, subject to normal media negotiation.

Declare a function module and pass it in the registry's `functions:` list:

```elixir
defmodule MyApp.API.Add do
  use PgRest.Function,
    schema: "public",
    name: "add_them",
    params: [{"a", "integer"}, {"b", "integer", default: true}],
    returns: {:scalar, "integer"},
    volatility: :immutable
end

{PgRest.Registry, modules: [MyApp.API.Tasks], functions: [MyApp.API.Add]}
```

`returns:` also accepts `:void`, `{:setof_scalar, type}`,
`{:composite, resource_module}` and `{:setof, resource_module}`; composite shapes
can instead list `{column, postgres_type}` pairs. Declare each overload separately.
See `PgRest.Function` for parameter defaults and variadic arguments.

## Introspection and exposure

```elixir
{PgRest.Registry,
  modules: [MyApp.API.Tasks],
  introspect: [repo: MyApp.Repo, only: ["add_them"], as_role: "api_user"]}
```

In default application mode, calls run as the repo role. Introspection requires
`only:`/`except:` or an `authorization:` module exporting `authorize/4`; use an
explicit allowlist for a small public API. `as_role:` filters functions by EXECUTE
privilege; it does not change the role executing calls. Extension-owned functions
and trigger, event_trigger and internal returns are never exposed. A declared
function replaces an introspected signature with the same schema, name and inputs.

For an RLS plug, use `introspect: [repo: MyApp.AuthenticatorRepo, mode: :rls]`.
The plug checks registry mode and authorization settings; Postgres enforces EXECUTE
as the request's role. `as_role:` defaults to `nil`: no EXECUTE catalog filter is
applied, matching PostgREST's schema cache. Functions unavailable to the request
role remain cached and fail with `42501` when called. Set `as_role:` explicitly
when you also want to filter the catalog.

## Scoped results

`result_scope: :stored_rows` is the default: a returned resource row survives only
when an in-scope stored row matches its key and every mapped column, using
`IS NOT DISTINCT FROM`. Fabricated rows and altered attributes are dropped.
Custom-scoped resources need a primary key or `unique_key:`. VOLATILE functions
returning custom-scoped resources must explicitly declare `result_scope: :none`:
this trusts the function to enforce row visibility. The result resource still needs
`:read`; its query hook may deny and still restricts columns, count, aggregates and
permission limits. Only row matching is skipped, without requiring a key. Introspected functions set options
through `function_opts: %{{"public", "function_name"} => [result_scope: :none]}`.
Types without equality operators also need `:none` for scoped result matching.

### Row order and function inlining

By default the call statement is PostgREST's (`callPlanToQuery`): the function is called once,
unnumbered, and the read adds an `ORDER BY` only for an `order` parameter. Without
`order`, rows come in the order Postgres yields them. For an inlinable function that
is the function's own `ORDER BY`, through filters, `limit`/`offset` and embeds, exactly
as in PostgREST. This is best effort: Postgres guarantees an order only for an explicit
`ORDER BY` of the outer query, so send `order=` (for example on a rank column the function
returns) when a page order must be guaranteed. Aggregating `select`s group the rows and
keep no order.

Declare `ordered: true` on a stable or immutable function returning `{:setof, Resource}`
to preserve its emitted order through filters, embeds and pagination. Give the function
a deterministic SQL ordering with a unique tie-breaker. PgRest numbers its rows before
checking the stored-row scope and orders the page by that private position. This can
require evaluating the entire function before pagination. Explicit root orders and
uncapped aggregate requests use the ordinary call. HEAD also skips numbering unless a
row cap applies before grouping. The position is unavailable to clients. PostgreSQL's `WITH ORDINALITY`
reserves the physical return-column name `ordinality`, including columns omitted from
the Ecto schema. Mapped conflicts fail registration. PostgreSQL rejects an unmapped
conflict as an ambiguous column (SQLSTATE 42702).

The stored-rows probe of a scoped call (`result_scope: :stored_rows`) is a correlated
`EXISTS (... OFFSET 0)` filter over the call. `OFFSET 0` stops Postgres from turning it
into a join, so the probe never reorders rows, and it does not block inlining.

Postgres inlines a function into the statement when it is `STABLE` or `IMMUTABLE`,
set-returning, `LANGUAGE sql`, not `STRICT` and not `SECURITY DEFINER`, free of `SET`
clauses (including `SET search_path`; schema-qualify names instead), a single `SELECT`
(ranking belongs in its `ORDER BY`), and called with arguments that contain no sub-selects
or volatile functions (PgRest's arguments never do). The request's filters are then pushed
into its body, and a `limit` can stop its scan early.

Any other function (for example `plpgsql`, whose `RETURN QUERY` always materializes)
runs to completion before the request's filters, `order` and `limit` apply. Check with
`Accept: application/vnd.pgrst.plan` (`plan_enabled: true`): an inlined function does
not appear in the plan.

Function authorization receives `%PgRest.Function{}`. Match `schema` and `name`
(and `params` for overloads); `module` is `nil` for introspected functions.

## Request bodies and function settings

A `POST` body is read by its `Content-Type`, as PostgREST does for a routine: JSON (also
without a Content-Type) names the arguments by its keys; `application/x-www-form-urlencoded`
passes its fields like a query string (a repeated field fills a `VARIADIC` parameter, any
other takes the last value; fields split on `&` only and malformed escapes are a 400 `PGRST100`); `text/plain`, `text/xml` and `application/octet-stream` reach
a single unnamed `text`, `xml` or `bytea` parameter. Any other type is a 400 `PGRST102`,
reported after the schema profile and the query string, as in PostgREST.

A form body needs the raw bytes, because the decoded map `Plug.Parsers` builds loses the
order and repeats of the fields: read it with `PgRest.BodyReader`, or leave `urlencoded` out
of `Plug.Parsers`. A form it already decoded is a 400 `PGRST102` instead of resolving
another overload.

A bare `RETURNS record` or `SETOF record` is returned as each record's JSON object, and a
domain over a composite type is that composite (its columns can be selected and filtered).

The `SET` clauses of an introspected function named in the plug's `hoisted_tx_settings`
(by default `statement_timeout`, `plan_filter.statement_cost_limit` and
`default_transaction_isolation`) apply to the whole call transaction, like PostgREST's
hoisted function settings. Postgres applies a function's own `SET` only while it runs,
which is too late for `statement_timeout`. A hoisted `statement_timeout` replaces the plug's
(it may be longer, and the client deadline follows it). A function's
`default_transaction_isolation` is the transaction's isolation level whether or not it is
listed, as in PostgREST; inside a transaction the caller already opened the caller's level
stands. A `SET` clause also stops Postgres from inlining the function.

## Errors and response overrides

`RAISE SQLSTATE 'PT402'` returns 402 with the database message, detail and hint.
`RAISE SQLSTATE 'PGRST'` reads MESSAGE JSON (`code`, `message`, optional `details`,
`hint`) and DETAIL JSON (`status`, `headers`, optional `status_text`). Invalid
payloads return 500 `PGRST121`. HTTP reason phrases are supplied by the host server.

Functions and triggers can set transaction-local `response.status` and
`response.headers` GUCs. Headers are a JSON array of single-key string objects;
repeated headers survive and replace generated headers of the same name. Status
must be in 200..999. Overrides are read in the main statement; any error rolls
back its side effects. Singular set-returning calls also roll back if the result
is not exactly one row, even with `tx=commit`.