39P02ERRORTier 2 — Caution✅ HIGH confidenceSRF 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
- 1A C extension set-returning function does not comply with Postgres SRF calling conventions
- 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.
Fix 1: Follow Postgres SRF calling conventions in C extensions
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 the SRF logic can be expressed in PL/pgSQL.
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 docs: https://www.postgresql.org/docs/current/errcodes-appendix.html
🔧 Source ref: Class 39 — External Routine Invocation Exception (Postgres-specific)
📖 Further reading: Postgres C Extension SRF API
Confidence assessment
✅ HIGH confidence
Postgres-specific. Stable across versions.
See also
📄 Reference pages