39P02
PostgreSQLERRORNotableExternal Routine Invocation ExceptionHIGH confidence

SRF protocol violated

What this means

SQLSTATE 39P02 is a Postgres-specific error raised when a set-returning function (SRF) violates the SRF calling protocol — for example, a C extension SRF that does not properly manage the FunctionCallInfoData or SRF context.

Why it happens
  1. 1A C extension set-returning function does not comply with Postgres SRF calling conventions
  2. 2Incorrect use of SRF_FIRSTCALL_INIT, SRF_PERCALL_SETUP, or SRF_RETURN_NEXT macros in C
How to reproduce

C extension SRF violating calling protocol.

expected output

ERROR:  set-valued function called in context that cannot accept a set

Fix 1

Follow Postgres SRF calling conventions in C extensions

WHEN When developing a C extension set-returning function.

Why this works

Use the SRF_FIRSTCALL_INIT, SRF_PERCALL_SETUP, SRF_RETURN_NEXT, and SRF_RETURN_DONE macros correctly as documented in the Postgres server programming guide.

Fix 2

Use PL/pgSQL RETURNS TABLE or RETURNS SETOF instead

WHEN When the SRF logic can be expressed in PL/pgSQL.

Use PL/pgSQL RETURNS TABLE or RETURNS SETOF instead
CREATE FUNCTION my_srf() RETURNS SETOF TEXT AS $
BEGIN
  RETURN NEXT 'row1';
  RETURN NEXT 'row2';
END;
$ LANGUAGE plpgsql;

Why this works

PL/pgSQL handles SRF protocol management automatically, avoiding the need to implement it manually in C.

Sources
Official documentation ↗

Class 39 — External Routine Invocation Exception (Postgres-specific)

Postgres C Extension SRF API

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PostgreSQL errors