fmgr-and-spilisted
Install: claude install-skill matejformanek/postgres-claude
# fmgr and SPI — operational playbook
The fmgr is how every SQL-callable C function in PostgreSQL gets invoked.
SPI is how that same C code runs SQL back into the executor. They sit
adjacent in any non-trivial extension or PL.
All confidence tags are `[verified-by-code]` unless noted.
---
## 1. Writing a SQL-callable C function (fmgr V1)
V0 ("old style") was removed; V1 is the only supported convention.
[verified-by-code] `src/include/fmgr.h:382-394` ("Version-0 ... is not supported anymore. Version 1 is the call convention defined in this header file").
### 1.1 Minimum boilerplate
```c
#include "postgres.h"
#include "fmgr.h"
PG_MODULE_MAGIC; /* exactly once per .so */
PG_FUNCTION_INFO_V1(my_func); /* once per exported func */
Datum
my_func(PG_FUNCTION_ARGS)
{
int32 a = PG_GETARG_INT32(0);
text *t = PG_GETARG_TEXT_PP(1);
/* ... */
PG_RETURN_INT32(a + VARSIZE_ANY_EXHDR(t));
}
```
`PG_FUNCTION_ARGS` expands to `FunctionCallInfo fcinfo`
[verified-by-code] `src/include/fmgr.h:193`.
`PG_FUNCTION_INFO_V1(name)` defines `pg_finfo_<name>()` returning
`{ api_version = 1 }`, marks the function `PGDLLEXPORT`, and (importantly)
emits an extern declaration of the C function so you don't have to
[verified-by-code] `src/include/fmgr.h:417-426`.
`PG_MODULE_MAGIC` (or `PG_MODULE_MAGIC_EXT(.name=..., .version=...)`)
must appear exactly once in a multi-source-file module
[verified-by-code] `src/include/fmgr.h:441-549