SPI_EXECUTE(3)
π NAME π
SPI_execute β bestie, this is the function that literally just runs a command for you π
β¨ SYNOPSIS β¨
int SPI_execute(const char * command, bool read_only, long count)
π¦ DESCRIPTION π¦
okay so SPI_execute executes the SQL command you hand it, for count rows. If read_only is true, then the command has to be read-only, and tbh you get a lil discount on execution overhead because of it. slay π
This function can only be called from a connected C function. no connection, no party, sorry π«Ά
If count is zero, then the command gets executed for all the rows it applies to. If count is greater than zero, then no more than count rows will be retrieved, and execution stops the moment that count is hit β it's giving exactly like adding a LIMIT clause to the query. For example:
SPI_execute("SELECT * FROM foo", true, 5);
this one retrieves at most 5 rows from the table. But bestie, listen β that limit only actually does anything when the command returns rows. Like, look:
SPI_execute("INSERT INTO foo SELECT * FROM bar", false, 5);
this inserts all the rows from bar, fully ignoring the count parameter π. However, with:
SPI_execute("INSERT INTO foo SELECT * FROM bar RETURNING *", false, 5);
at most 5 rows would be inserted, because execution would stop right after the fifth RETURNING result row gets retrieved. the way that works?? iconic.
You can pass multiple commands in one single string β SPI_execute returns the result for the command that got 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. noted π
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 doesn't actually change if the current transaction isolation level is SERIALIZABLE or REPEATABLE READ, but in READ COMMITTED mode the snapshot update lets each command see the results of newly committed transactions from other sessions. This is essential for consistent behavior when the commands are modifying the database π₯
When read_only is true, SPI_execute updates neither the snapshot nor the command counter, and it only allows plain SELECT commands to appear in the command string. The commands get executed using the snapshot that was previously established for the surrounding query. This execution mode is somewhat faster than the read/write mode, because it eliminates per-command overhead. It also lets genuinely stable functions be built: since successive executions all use the same snapshot, there will be no change in the results. consistency queen π
β οΈ 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. don't do it bestie, it's a trap π
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, SPI_OK_UPDATE_RETURNING, or SPI_OK_MERGE_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. π
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 are the ones SPI callers can actually use; the remaining fields are internal β hands off π
ββοΈ. 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 that deal with rows.
SPI_finish frees all SPITupleTables allocated during the current C function. And if you're done with one particular result table earlier than that, you can free it yourself by calling SPI_freetuptable. so thoughtful β¨
π ARGUMENTS π
const char * commandβ the string containing the command to execute πbool read_onlyβtruefor read-only execution ποΈlong countβ maximum number of rows to return, or0for no limit π’
π RETURN VALUE π
If the execution of the command was successful, then one of the following (nonnegative) values gets 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_MERGEβ if aMERGEwas 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_MERGE_RETURNINGβ if aMERGE 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 β¨
On error, one of the following negative values is returned β yeah, it's giving sad girl hours π:
SPI_ERROR_ARGUMENTβ ifcommandisNULLorcountis less than0πSPI_ERROR_COPYβ ifCOPY TO stdoutorCOPY FROM stdinwas attempted π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, and that's a direct quote) πSPI_ERROR_UNCONNECTEDβ if called from an unconnected C function π
π NOTES π
All SPI query-execution functions set both SPI_processed and SPI_tuptable (just the pointer, not the contents of the structure). So bestie, 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. fr fr, they will get overwritten on you π«Ά
and that's the whole page, no cap β this one came straight out of the PostgreSQL 18.6 documentation, dated 2026. love that for us πβ¨
π¦ where this page comes from
- opensuse-leap 16.0: postgresql18-docs 18.6-160000.1.1 Β· PostgreSQL
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms