Home Explore Blog CI



postgresql

51th chunk of `doc/src/sgml/spi.sgml`
0eaf5936263e73f1b182f9d115a40a8816cf866e236194d70000000100000868
 second, executes the command
   using <function>SPI_exec</function> and returns the number of rows
   that were processed by the command.  You can find more complex
   examples for SPI in the source tree in
   <filename>src/test/regress/regress.c</filename> and in the
   <xref linkend="contrib-spi"/> module.
  </para>

<programlisting>
#include "postgres.h"

#include "executor/spi.h"
#include "utils/builtins.h"

PG_MODULE_MAGIC;

PG_FUNCTION_INFO_V1(execq);

Datum
execq(PG_FUNCTION_ARGS)
{
    char *command;
    int cnt;
    int ret;
    uint64 proc;

    /* Convert given text object to a C string */
    command = text_to_cstring(PG_GETARG_TEXT_PP(0));
    cnt = PG_GETARG_INT32(1);

    SPI_connect();

    ret = SPI_exec(command, cnt);

    proc = SPI_processed;

    /*
     * If some rows were fetched, print them via elog(INFO).
     */
    if (ret &gt; 0 &amp;&amp; SPI_tuptable != NULL)
    {
        SPITupleTable *tuptable = SPI_tuptable;
        TupleDesc tupdesc = tuptable-&gt;tupdesc;
        char buf[8192];
        uint64 j;

        for (j = 0; j &lt; tuptable-&gt;numvals; j++)
        {
            HeapTuple tuple = tuptable-&gt;vals[j];
            int i;

            for (i = 1, buf[0] = 0; i &lt;= tupdesc-&gt;natts; i++)
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %s%s",
                        SPI_getvalue(tuple, tupdesc, i),
                        (i == tupdesc-&gt;natts) ? " " : " |");
            elog(INFO, "EXECQ: %s", buf);
        }
    }

    SPI_finish();
    pfree(command);

    PG_RETURN_INT64(proc);
}
</programlisting>

  <para>
   This is how you declare the function after having compiled it into
   a shared library (details are in <xref linkend="dfunc"/>.):

<programlisting>
CREATE FUNCTION execq(text, integer) RETURNS int8
    AS '<replaceable>filename</replaceable>'
    LANGUAGE C STRICT;
</programlisting>
  </para>

  <para>
   Here is a sample session:

<programlisting>
=&gt; SELECT execq('CREATE TABLE a (x integer)', 0);
 execq
-------
     0
(1 row)

=&gt; INSERT INTO a VALUES (execq('INSERT INTO a VALUES (0)', 0));
INSERT 0 1
=&gt; SELECT execq('SELECT

Title: Example SPI Usage: The `execq` Function
Summary
This section provides a concrete example of using the SPI (Server Programming Interface) in PostgreSQL. It showcases a C function named `execq` that takes an SQL command and a row count as input. The function uses `SPI_exec` to execute the command and returns the number of rows processed. The example includes the C code for `execq`, along with instructions on how to declare the function in SQL after compiling it into a shared library. It also demonstrates a sample session illustrating how to call the `execq` function.