SPI_EXECUTE(3)

πŸ“¦ version 15.19, in opensuse-leap 16.0

πŸ’… SPI_EXECUTE(3) β€” the PostgreSQL 15.19 glow-up

okay bestie, welcome to SPI_execute, from the PostgreSQL 15.19 Documentation era, and this is genuinely one of the most used functions in the whole SPI cinematic universe, so let's get into it πŸŽ€


✨ NAME ✨

SPI_execute β€” execute a command. that's it. that's the whole name. iconic brevity πŸ’–


✨ SYNOPSIS ✨

int SPI_execute(const char * command, bool read_only, long count)

three args, one int back, no drama πŸ¦‹


✨ DESCRIPTION ✨

so SPI_execute executes the SQL command you hand it, for count rows. and if read_only is true, the command must be read-only β€” but the payoff is that execution overhead is somewhat reduced, so that's the vibe check paying off πŸ”₯

🚨 this function can only be called from a connected C function. like, connected-connected. not the lonely unconnected kind.

Now the count lore, because it's giving nuance:

  • if count is zero, the command executes for all rows it applies to.
  • if count is greater than zero, then no more than count rows will be retrieved, and execution stops when count is reached β€” much like adding a LIMIT clause to the query.

example time, and yes I will be saying "for example" every time the original does πŸ’…

SPI_execute("SELECT * FROM foo", true, 5);

that one retrieves at most 5 rows from the table. cute.

⚠️ but note that such a limit is only effective when the command actually returns rows. so like, read that twice.
SPI_execute("INSERT INTO foo SELECT * FROM bar", false, 5);

that inserts all rows from bar, completely ignoring the count parameter. it said "no cap, all of them." πŸ’€

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. the RETURNING was the main character there, honestly πŸ‘‘

You can pass multiple commands in one string β€” go off β€” and 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). and the limit is not applied to any hidden commands generated by rules. rules said "not my problem" 🧚

read_only = false

When read_only is false, SPI_execute increments the command counter and computes a new snapshot before executing each command in the string.

okay so 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. literally essential. fr fr πŸ’œ

read_only = true

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 🌸

πŸ™ˆ warning bestie: 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. please. i'm begging.

results, rows, and tuples

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 don't panic when it's NULL, it's fine 🫢

The structure SPITupleTable is defined thus β€” copying exactly, character for character:

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 πŸ’–

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. clean up after yourself, bestie πŸŽ€


✨ ARGUMENTS ✨

  • const char * command β€” string containing command to execute πŸ’…
  • bool read_only β€” true for read-only execution
  • long count β€” maximum number of rows to return, or 0 for no limit

✨ RETURN VALUE ✨

If the execution of the command was successful then one of the following (nonnegative) values will be returned 😌✨

  • SPI_OK_SELECT β€” if a SELECT (but not SELECT INTO) was executed
  • SPI_OK_SELINTO β€” if a SELECT INTO was executed
  • SPI_OK_INSERT β€” if an INSERT was executed
  • SPI_OK_DELETE β€” if a DELETE was executed
  • SPI_OK_UPDATE β€” if an UPDATE was executed
  • SPI_OK_MERGE β€” if a MERGE was executed
  • SPI_OK_INSERT_RETURNING β€” if an INSERT RETURNING was executed
  • SPI_OK_DELETE_RETURNING β€” if a DELETE RETURNING was executed
  • SPI_OK_UPDATE_RETURNING β€” if an UPDATE RETURNING was 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., UPDATE became an INSERT) by a rule.

On error, one of the following negative values is returned 😭 (negative, as in bad vibes)

  • SPI_ERROR_ARGUMENT β€” if command is NULL or count is less than 0
  • SPI_ERROR_COPY β€” if COPY TO stdout or COPY FROM stdin was 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 πŸ™ˆ)
  • 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 listen up 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. otherwise the globals will move on without you and you'll be left on read πŸ’€πŸ«Ά


and that's the whole page, bestie β€” go execute something responsibly πŸ’œ

sign-off time πŸŽ€ β€” this was PostgreSQL 15.19, dated 2026, manual page SPI_EXECUTE(3). slay, and see you in the next call ✨

πŸ“¦ where this page comes from