PG
PRO
39P02ERRORTier 2 — Caution✅ HIGH confidence

SRF protocol violated

Category: External Routine Invocation ExceptionVersions: All Postgres versions

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.

trigger — this will ERROR
ERROR: set-valued function called in context that cannot accept a set

Fix 1: Follow Postgres SRF calling conventions in C extensions

When developing a C extension set-returning function.

fix

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.

fix
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

C ExtensionsSet-Returning FunctionsRETURNS SETOF
⚙️ This error reference was generated with AI assistance and reviewed for accuracy. Examples are provided to illustrate common scenarios and may not cover every case. Always test fixes in a development environment before applying to production. Spotted an error? Suggest a correction →