SPI_EXECUTE(3)
π SPI_EXECUTE(3) β the PostgreSQL one, bestie β¨
okay so you're in the PostgreSQL 14.24 docs, specifically the C function section, and we're about to talk about SPI_execute π this is the one that actually runs your SQL from inside a C function, and honestly? iconic.
πΈ NAME πΈ
SPI_execute β execute a command (yes bestie, literally just run the SQL, that's the whole vibe) π₯
β¨ SYNOPSIS β¨
int SPI_execute(const char * command, bool read_only, long count)
that's the signature, don't @ me, copy it exactly π«Ά
π¦ DESCRIPTION π¦
so SPI_execute executes the SQL command you give it, for count rows. if read_only is true, the command must be read-only (no sneaky writes, bestie π), and the execution overhead is somewhat reduced β which is giving efficiency queen energy ngl.
this function can only be called from a connected C function. not connected? not happening. SPI_ERROR_UNCONNECTED is waiting for you π
if count is zero, then the command is executed for all rows that it applies to. if count is greater than zero, then no more than count rows will be retrieved; execution stops when the count is reached, much like adding a LIMIT clause to the query. for example:
SPI_execute("SELECT * FROM foo", true, 5);
this will retrieve at most 5 rows from the table. note that such a limit is only effective when the command actually returns rows. for example:
SPI_execute("INSERT INTO foo SELECT * FROM bar", false, 5);
inserts all rows from bar, ignoring the count parameter. the limit said "not today" π. however, with:
SPI_execute("INSERT INTO foo SELECT * FROM bar RETURNING *", false, 5);
at most 5 rows would be inserted, since execution would stop after the fifth RETURNING result row is retrieved. RETURNING really said "I'll make the limit work" and slayed π
you can pass multiple commands in one string; SPI_execute returns the result for the command executed last. the count limit applies to each command separately (even though only the last result will actually be returned). the limit is not applied to any hidden commands generated by rules. rules do what they want, no cap.
when read_only is false, SPI_execute increments the command counter and computes a new snapshot before executing each command in the string. the snapshot does not actually change if the current transaction isolation level is SERIALIZABLE or REPEATABLE READ, but in READ COMMITTED mode the snapshot update allows each command to see the results of newly committed transactions from other sessions. this is essential for consistent behavior when the commands are modifying the database. consistency is the moment β¨
when read_only is true, SPI_execute does not update either the snapshot or the command counter, and it allows only plain SELECT commands to appear in the command string. the commands are executed using the snapshot previously established for the surrounding query. this execution mode is somewhat faster than the read/write mode due to eliminating per-command overhead. it also allows genuinely stable functions to be built: since successive executions will all use the same snapshot, there will be no change in the results. stable queen behavior π
it is generally unwise to mix read-only and read-write commands within a single function using SPI; that could result in very confusing behavior, since the read-only queries would not see the results of any database updates done by the read-write queries. mixing them is giving chaos and we don't stan chaos π ββοΈ
the actual number of rows for which the (last) command was executed is returned in the global variable SPI_processed. if the return value of the function is SPI_OK_SELECT, SPI_OK_INSERT_RETURNING, SPI_OK_DELETE_RETURNING, or SPI_OK_UPDATE_RETURNING, then you can use the global pointer SPITupleTable *SPI_tuptable to access the result rows. some utility commands (such as EXPLAIN) also return row sets, and SPI_tuptable will contain the result in these cases too. some utility commands (COPY, CREATE TABLE AS) don't return a row set, so SPI_tuptable is NULL, but they still return the number of rows processed in SPI_processed. so even when there's no row set, the count still pulls up π
the structure SPITupleTable is defined thus:
typedef struct SPITupleTable
{
/* Public members */
TupleDesc tupdesc; /* tuple descriptor */
HeapTuple *vals; /* array of tuples */
uint64 numvals; /* number of valid tuples */
/* Private members, not intended for external callers */
uint64 alloced; /* allocated length of vals array */
MemoryContext tuptabcxt; /* memory context of result table */
slist_node next; /* link for internal bookkeeping */
SubTransactionId subid; /* subxact in which tuptable was created */
} SPITupleTable;
the fields tupdesc, vals, and numvals can be used by SPI callers; the remaining fields are internal. vals is an array of pointers to rows. the number of rows is given by numvals (for somewhat historical reasons, this count is also returned in SPI_processed). tupdesc is a row descriptor which you can pass to SPI functions dealing with rows. so tupdesc, vals, numvals are the public besties, the rest are private and we respect their privacy π«Ά
SPI_finish frees all SPITupleTables allocated during the current C function. you can free a particular result table earlier, if you are done with it, by calling SPI_freetuptable. freeing early is self-care β¨
π ARGUMENTS π
const char * commandβ string containing command to execute. yes, the SQL goes here, bestie.bool read_onlyβtruefor read-only execution. no writes allowed when this is on, periodt.long countβ maximum number of rows to return, or0for no limit.0means "give me everything" π
π RETURN VALUE π
if the execution of the command was successful then one of the following (nonnegative) values will be returned:
SPI_OK_SELECTβ if aSELECT(but notSELECT INTO) was executed β¨SPI_OK_SELINTOβ if aSELECT INTOwas executed πSPI_OK_INSERTβ if anINSERTwas executed πSPI_OK_DELETEβ if aDELETEwas executed π¦SPI_OK_UPDATEβ if anUPDATEwas executed πΈSPI_OK_INSERT_RETURNINGβ if anINSERT RETURNINGwas executed πSPI_OK_DELETE_RETURNINGβ if aDELETE RETURNINGwas executed π₯SPI_OK_UPDATE_RETURNINGβ if anUPDATE RETURNINGwas executed πSPI_OK_UTILITYβ if a utility command (e.g.,CREATE TABLE) was executed πSPI_OK_REWRITTENβ if the command was rewritten into another kind of command (e.g.,UPDATEbecame anINSERT) by a rule. rules said "plot twist" π
on error, one of the following negative values is returned:
SPI_ERROR_ARGUMENTβ ifcommandisNULLorcountis less than0πSPI_ERROR_COPYβ ifCOPY TO stdoutorCOPY FROM stdinwas attempted. not here, bestie π«SPI_ERROR_TRANSACTIONβ if a transaction manipulation command was attempted (BEGIN,COMMIT,ROLLBACK,SAVEPOINT,PREPARE TRANSACTION,COMMIT PREPARED,ROLLBACK PREPARED, or any variant thereof) πSPI_ERROR_OPUNKNOWNβ if the command type is unknown (shouldn't happen β but if it does, something is deeply wrong π)SPI_ERROR_UNCONNECTEDβ if called from an unconnected C function. connect first, babes π«Ά
β NOTES β
all SPI query-execution functions set both SPI_processed and SPI_tuptable (just the pointer, not the contents of the structure). save these two global variables into local C function variables if you need to access the result table of SPI_execute or another query-execution function across later calls. don't lose your globals, bestie, they're fragile π
fr fr, the way that this function carries the whole SPI execution game... it's giving main character energy and we love to see it π
PostgreSQL 14.24, dated 2026 β that's the source and version, bestie, and honestly this man page ate and left no crumbs π β¨ππ¦ππΈπ«Άπ₯ππ
π¦ where this page comes from
- opensuse-leap 16.0: postgresql14-docs 14.24-160000.1.1 Β· PostgreSQL
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms