Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@ becomes the release notes of the next tag.

## [Unreleased]

### Fixed

- **Volatile `SETOF` RPCs ran more than once or not at all.** `count=true`
executed a volatile set-returning function twice (rows, then the total),
and `limit=0` on a `SETOF <scalar>` or `SETOF <composite>` one compiled to
`LIMIT 0`, so the function never ran while the `SETOF <table>` form did.
A volatile set-returning function now runs exactly once per request
whatever `count`, `limit`, `offset` or `limit=0` say: its output is
materialised in a CTE that the page, the `has_next` look-ahead and the
total read. `limit=0` is consistent across result kinds (function runs
once, no rows, total still reported). Stable and immutable functions are
unchanged.

## [0.20.0] - 2026-11-24

### Security
Expand Down
13 changes: 11 additions & 2 deletions docs/rpc.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,8 +234,17 @@ exception is the `auth.mint_type` composite: it is emitted raw
(`to_jsonb(__fn.v)`, shapes `jwt` / `jwt_set`) so the claims keep their JSON
numbers (`exp` must be numeric for verification), and exec signs them.

Volatile functions use exactly the same shapes; only the transaction policy
differs.
Volatile functions use the same shapes and the same transaction policy as
above, with one difference for set-returning ones: the call is evaluated
exactly once per request, whatever `count`, `limit`, `offset` or `limit=0`
say. The compiler materialises it in a leading
`WITH __call AS MATERIALIZED (SELECT ... FROM fn(...))` CTE and the page, the
`has_next` look-ahead row and the `count=true` total all read that CTE
instead of calling the function again. `limit=0` returns no rows for every
result kind (`SETOF <table>`, `SETOF <scalar>`, `SETOF <composite>`), still
runs the function once, and still reports the total under `count=true`.
Stable and immutable functions keep the plain `FROM fn(...)` plan: they have
no side effects, so re-reading them is invisible.

## Volatile functions are mutations

Expand Down
6 changes: 5 additions & 1 deletion internal/compile/golden_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,10 @@ func goldenCatalog() *introspect.Catalog {
},
}, &introspect.Function{
Schema: "public", Name: "post_array", ReturnType: "_posts", ReturnTypeSchema: "public", Volatility: introspect.VolatilityStable,
}, &introspect.Function{
Schema: "public", Name: "vol_posts", ReturnType: "posts", ReturnTypeSchema: "public", ReturnsSet: true, Volatility: introspect.VolatilityVolatile,
}, &introspect.Function{
Schema: "public", Name: "vol_ints", ReturnType: "int4", ReturnTypeSchema: pg, ReturnsSet: true, Volatility: introspect.VolatilityVolatile,
}, &introspect.Function{
Schema: "public", Name: "post_tab", ReturnType: "record", ReturnTypeSchema: pg, ReturnsSet: true, Volatility: introspect.VolatilityStable,
ReturnColumns: []introspect.FuncArg{
Expand Down Expand Up @@ -357,7 +361,7 @@ func TestGolden(t *testing.T) {
}

// goldenOnlyRPCs are the functions goldenCatalog adds to the fixture.
var goldenOnlyRPCs = map[string]bool{"noop": true, "greet": true, "sum_all": true, "mood_counts": true, "user_stats": true, "post_array": true, "post_tab": true}
var goldenOnlyRPCs = map[string]bool{"noop": true, "greet": true, "sum_all": true, "mood_counts": true, "user_stats": true, "post_array": true, "post_tab": true, "vol_posts": true, "vol_ints": true}

// TestGoldenAgainstDatabase executes every golden statement against the
// live fixture database (PDBR_TEST_DATABASE_URL; skipped otherwise), each in
Expand Down
69 changes: 52 additions & 17 deletions internal/compile/rpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,8 @@ func (s *stmt) rpcValue(rpc *api.RPC, call string) (*Statement, error) {
// over a composite or row type, whose values a FROM item also expands into
// columns, so the whole row is read): the function output, bounded by
// limit/offset (max_page_size when absent), aggregated in output order
// into a JSON array.
// into a JSON array. A volatile function is evaluated once in a materialized
// CTE; limit=0 then returns [] after reading it for its side effects.
func (s *stmt) rpcSetOfValues(rpc *api.RPC, call string) (*Statement, error) {
fn := rpc.Function
limit, err := s.embedLimit(s.plan.Page)
Expand All @@ -209,29 +210,55 @@ func (s *stmt) rpcSetOfValues(rpc *api.RPC, call string) (*Statement, error) {
if s.plan.Page.Offset < 0 {
return nil, errUser(CodeInvalidParameter, "offset must be >= 0")
}
once := rpc.Mutation
if once && limit == 0 {
cte := s.callCTE(valueSource(rpc, s.structuredReturn(fn), call))
return &Statement{SQL: cte + "SELECT '[]'::json AS data\nFROM (SELECT count(*) FROM " + callCTEName + ") AS __n", Shape: setShape(rpc)}, nil
}
pageSQL := " LIMIT " + strconv.Itoa(limit)
if s.plan.Page.Offset > 0 {
pageSQL += " OFFSET " + s.param(s.plan.Page.Offset)
}
var from, expr string
shape := ShapeScalar
switch {
case rpc.Mint:
from = fmt.Sprintf("(SELECT __v AS v FROM %s AS __v%s) AS __s", call, pageSQL)
expr = "to_jsonb(__s.v)"
shape = ShapeJWTSet
case rpc.Returns == api.ReturnSetOfComposite, s.structuredReturn(fn) != nil && !strings.HasPrefix(fn.ReturnType, "_"):
from = fmt.Sprintf("(SELECT __v AS v FROM %s AS __v%s) AS __s", call, pageSQL)
if expr, err = s.valueJSON("__s.v", fn, 0); err != nil {
return nil, err
}
default:
from = fmt.Sprintf("(SELECT __v.v FROM %s AS __v(v)%s) AS __s", call, pageSQL)
src := valueSource(rpc, s.structuredReturn(fn), call)
prefix := ""
if once {
prefix = s.callCTE(src)
src = "SELECT v FROM " + callCTEName
}
expr := "to_jsonb(__s.v)"
if !rpc.Mint {
if expr, err = s.valueJSON("__s.v", fn, 0); err != nil {
return nil, err
}
}
return &Statement{SQL: fmt.Sprintf("SELECT coalesce(json_agg(%s), '[]'::json) AS data\nFROM %s", expr, from), Shape: shape}, nil
return &Statement{SQL: fmt.Sprintf("%sSELECT coalesce(json_agg(%s), '[]'::json) AS data\nFROM (%s%s) AS __s", prefix, expr, src, pageSQL), Shape: setShape(rpc)}, nil
}

// callCTEName names the CTE that holds a volatile function's output.
const callCTEName = "__call"

// callCTE renders the leading WITH clause that evaluates a volatile
// set-returning function exactly once; every later read of the output
// (page, look-ahead row, total) scans this CTE instead of calling the
// function again.
func (s *stmt) callCTE(query string) string {
return "WITH " + callCTEName + " AS MATERIALIZED (" + query + ")\n"
}

// valueSource renders the query yielding one column v per output value of a
// SETOF <scalar|composite> call.
func valueSource(rpc *api.RPC, structured *introspect.Column, call string) string {
if rpc.Mint || rpc.Returns == api.ReturnSetOfComposite || structured != nil && !strings.HasPrefix(rpc.Function.ReturnType, "_") {
return fmt.Sprintf("SELECT __v AS v FROM %s AS __v", call)
}
return fmt.Sprintf("SELECT __v.v FROM %s AS __v(v)", call)
}

func setShape(rpc *api.RPC) Shape {
if rpc.Mint {
return ShapeJWTSet
}
return ShapeScalar
}

// rpcNode returns the projection node for a table-returning function.
Expand Down Expand Up @@ -272,15 +299,23 @@ func (s *stmt) rpcRow(rpc *api.RPC, call string) (*Statement, error) {
// rpcSetOfRows compiles SETOF <table>: the list compiler over the function
// call as the root row source. Cursors are off (function output has no
// stable keyset), so the page carries offset links only; the count subquery
// re-renders the same call, reusing the argument parameters.
// re-renders the same call, reusing the argument parameters. A volatile
// function is evaluated once in a materialized CTE that the page and the
// count both read.
func (s *stmt) rpcSetOfRows(rpc *api.RPC, call string) (*Statement, error) {
p := *s.plan
p.Resource = rpc.Resource
s.plan = &p
s.rootSource = call
if !rpc.Mutation {
return s.list()
}
columns := s.callCTE("SELECT * FROM " + call)
s.rootSource = callCTEName
st, err := s.list()
if err != nil {
return nil, err
}
st.SQL = columns + st.SQL
return st, nil
}
1 change: 1 addition & 0 deletions internal/compile/testdata/rpc_volatile_rows_count.http
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
POST /api/rpc/vol_posts?limit=2&offset=1&count=true
11 changes: 11 additions & 0 deletions internal/compile/testdata/rpc_volatile_rows_count.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-- request: POST /api/rpc/vol_posts?limit=2&offset=1&count=true
WITH __call AS MATERIALIZED (SELECT * FROM "public"."vol_posts"())
SELECT json_build_object('has_next', coalesce(bool_or(s1.__rn > $2), false), 'has_prev', true, 'total', (SELECT count(*) FROM __call c2), 'n', count(*) FILTER (WHERE s1.__rn <= $2), 'rows', coalesce(json_agg(s1.data ORDER BY s1.__rn ASC) FILTER (WHERE s1.__rn <= $2), '[]'::json)) AS data
FROM (
SELECT json_build_object('id', t0."id", 'author_id', t0."author_id", 'title', t0."title", 'body', t0."body", 'published', t0."published") AS data, row_number() OVER (ORDER BY t0."id" ASC) AS __rn
FROM __call t0
ORDER BY t0."id" ASC
LIMIT 3
OFFSET $1
) s1
-- args: [1,3]
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
POST /api/rpc/vol_posts?limit=0&count=true
10 changes: 10 additions & 0 deletions internal/compile/testdata/rpc_volatile_rows_limit_zero.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
-- request: POST /api/rpc/vol_posts?limit=0&count=true
WITH __call AS MATERIALIZED (SELECT * FROM "public"."vol_posts"())
SELECT json_build_object('has_next', coalesce(bool_or(s1.__rn > $1), false), 'has_prev', false, 'total', (SELECT count(*) FROM __call c2), 'n', count(*) FILTER (WHERE s1.__rn <= $1), 'rows', coalesce(json_agg(s1.data ORDER BY s1.__rn ASC) FILTER (WHERE s1.__rn <= $1), '[]'::json)) AS data
FROM (
SELECT NULL::json AS data, row_number() OVER (ORDER BY t0."id" ASC) AS __rn
FROM __call t0
ORDER BY t0."id" ASC
LIMIT 1
) s1
-- args: [0]
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
POST /api/rpc/vol_ints?limit=0
5 changes: 5 additions & 0 deletions internal/compile/testdata/rpc_volatile_values_limit_zero.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- request: POST /api/rpc/vol_ints?limit=0
WITH __call AS MATERIALIZED (SELECT __v.v FROM "public"."vol_ints"() AS __v(v))
SELECT '[]'::json AS data
FROM (SELECT count(*) FROM __call) AS __n
-- args: []
1 change: 1 addition & 0 deletions internal/compile/testdata/rpc_volatile_values_page.http
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
POST /api/rpc/vol_ints?limit=3&offset=1
5 changes: 5 additions & 0 deletions internal/compile/testdata/rpc_volatile_values_page.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- request: POST /api/rpc/vol_ints?limit=3&offset=1
WITH __call AS MATERIALIZED (SELECT __v.v FROM "public"."vol_ints"() AS __v(v))
SELECT coalesce(json_agg(to_json(__s.v)), '[]'::json) AS data
FROM (SELECT v FROM __call LIMIT 3 OFFSET $1) AS __s
-- args: [1]
136 changes: 136 additions & 0 deletions test/e2e_volatile_once_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package e2e

import (
"context"
"encoding/json"
"os"
"testing"

"github.com/jackc/pgx/v5"

"github.com/suprbdev/pdbr/internal/config"
)

func TestVolatileSetReturningRunsOnce(t *testing.T) {
dbURL := os.Getenv("PDBR_TEST_DATABASE_URL")
if dbURL == "" {
t.Skip("PDBR_TEST_DATABASE_URL not set")
}
ctx := context.Background()
conn, err := pgx.Connect(ctx, dbURL)
if err != nil {
t.Fatal(err)
}
defer conn.Close(ctx)
t.Cleanup(func() {
c, err := pgx.Connect(ctx, dbURL)
if err != nil {
t.Errorf("cleanup: %v", err)
return
}
defer c.Close(ctx)
_, _ = c.Exec(ctx, `DROP FUNCTION IF EXISTS public.e2e_once_rows(), public.e2e_once_scalar(), public.e2e_once_composite(), public.e2e_once_stable_rows();
DROP TYPE IF EXISTS public.e2e_once_pair; DROP TABLE IF EXISTS public.e2e_once_calls`)
})
setup := `
DROP TABLE IF EXISTS public.e2e_once_calls CASCADE;
CREATE TABLE public.e2e_once_calls (fn text NOT NULL);
GRANT ALL ON public.e2e_once_calls TO PUBLIC;
CREATE TYPE public.e2e_once_pair AS (a int, b text);
CREATE FUNCTION public.e2e_once_rows() RETURNS SETOF public.posts LANGUAGE plpgsql VOLATILE AS $$
BEGIN
INSERT INTO public.e2e_once_calls VALUES ('rows');
RETURN QUERY SELECT * FROM public.posts ORDER BY id LIMIT 4;
END $$;
CREATE FUNCTION public.e2e_once_scalar() RETURNS SETOF int LANGUAGE plpgsql VOLATILE AS $$
BEGIN
INSERT INTO public.e2e_once_calls VALUES ('scalar');
RETURN QUERY SELECT g FROM generate_series(1, 4) g;
END $$;
CREATE FUNCTION public.e2e_once_composite() RETURNS SETOF public.e2e_once_pair LANGUAGE plpgsql VOLATILE AS $$
BEGIN
INSERT INTO public.e2e_once_calls VALUES ('composite');
RETURN QUERY SELECT g, 'x' || g FROM generate_series(1, 4) g;
END $$`
if _, err := conn.Exec(ctx, setup); err != nil {
t.Fatal(err)
}
if n := dbInt(t, `SELECT count(*) FROM posts`); n < 4 {
t.Skipf("fixture has %d posts, need 4", n)
}
srv := testServer(t, nil).URL
rb := testServer(t, func(c *config.Config) { c.TX.End = "rollback" }).URL

type result struct {
rows int
total string
}
reqs := []struct {
name string
path string
hdr map[string]string
want result
}{
{"plain", "", nil, result{4, ""}},
{"count", "?count=true", nil, result{4, "4"}},
{"limit=0", "?limit=0", nil, result{0, ""}},
{"limit=0 count", "?limit=0&count=true", nil, result{0, "4"}},
{"limit offset count", "?limit=2&offset=1&count=true", nil, result{2, "4"}},
{"offset", "?offset=3", nil, result{1, ""}},
{"offset at end count", "?offset=4&count=true", nil, result{0, "4"}},
{"range", "", map[string]string{"Range": "1-2", "Range-Unit": "items"}, result{-1, ""}},
{"range count", "", map[string]string{"Range": "1-2", "Range-Unit": "items", "Prefer": "count=exact"}, result{-1, ""}},
{"count planned", "?count=true", map[string]string{"Prefer": "count=planned"}, result{4, "4"}},
{"count estimated", "?count=true", map[string]string{"Prefer": "count=estimated"}, result{4, "4"}},
}
for _, fn := range []struct {
name, tag string
counted bool
}{
{"e2e_once_rows", "rows", true},
{"e2e_once_scalar", "scalar", false},
{"e2e_once_composite", "composite", false},
} {
for _, rq := range reqs {
if _, err := conn.Exec(ctx, `TRUNCATE public.e2e_once_calls`); err != nil {
t.Fatal(err)
}
res, body := send(t, "POST", srv+"/api/rpc/"+fn.name+rq.path, "{}", rq.hdr)
if res.StatusCode != 200 && res.StatusCode != 206 {
t.Errorf("%s %s: status %d %s", fn.name, rq.name, res.StatusCode, body)
continue
}
calls := dbInt(t, `SELECT count(*) FROM public.e2e_once_calls WHERE fn = '`+fn.tag+`'`)
if calls != 1 {
t.Errorf("%s %s: function ran %d times, want 1", fn.name, rq.name, calls)
}
if n := len(decodeRows(t, body)); rq.want.rows >= 0 && n != rq.want.rows {
t.Errorf("%s %s: %d rows, want %d (%s)", fn.name, rq.name, n, rq.want.rows, body)
}
if fn.counted && rq.want.total != "" {
if got := res.Header.Get("X-Total-Count"); got != rq.want.total {
t.Errorf("%s %s: X-Total-Count %q, want %q", fn.name, rq.name, got, rq.want.total)
}
}
}
if _, err := conn.Exec(ctx, `TRUNCATE public.e2e_once_calls`); err != nil {
t.Fatal(err)
}
res, body := send(t, "POST", rb+"/api/rpc/"+fn.name+"?count=true", "{}", nil)
if res.StatusCode != 200 || len(decodeRows(t, body)) != 4 {
t.Errorf("%s rollback: %d %s", fn.name, res.StatusCode, body)
}
if calls := dbInt(t, `SELECT count(*) FROM public.e2e_once_calls`); calls != 0 {
t.Errorf("%s rollback: %d calls survived", fn.name, calls)
}
}
}

func decodeRows(t *testing.T, body []byte) []json.RawMessage {
t.Helper()
var rows []json.RawMessage
if err := json.Unmarshal(body, &rows); err != nil {
t.Fatalf("body %s: %v", body, err)
}
return rows
}
Loading