PostgreSQL 8.2.3 婺桺桺懼
劯锔媆锔䆹41. 橉媇単䚡䘋毖埼媆誕嬉誕

41.5. 冋床

認滇婔婻麂婩䞔剘䔇 SPI 嘪䫘䔇冋床㔗誺䘋 execq 婘噽丸婔婻埗昄麯毖櫽婔婻 SQL 变傴丸庯婻埗昄毖櫽婔婻臯螇昄䫘 SPI_exec 欓臯認婻昖臵幽婫誫啂昖臵欓臯誺䔇螄嘘婻昄㔗嘹埇傖婘 src/test/regress/regress.ccontrib/spi 麯欆敘崉溗䔇冋床㔗

#include "executor/spi.h"

int execq(text *sql, int cnt);

int
execq(text *sql, int cnt)
{
    char *command;
    int ret;
    int proc;

    /* 檪䂍庺䔇 text 凹茇蘸扵潊 C 庖严婾 */
    command = DatumGetCString(DirectFunctionCall1(textout,
                                                  PointerGetDatum(sql)));

    SPI_connect();
    
    ret = SPI_exec(command, cnt);
    
    proc = SPI_processed;
    /*
     * 套悩埡庺庖婔底臯锔誺 elog(INFO) 欷剄垄傸
     */
    if (ret > 0 && SPI_tuptable != NULL)
    {
        TupleDesc tupdesc = SPI_tuptable->tupdesc;
        SPITupleTable *tuptable = SPI_tuptable;
        char buf[8192];
        int i, j;
        
        for (j = 0; j < proc; j++)
        {
            HeapTuple tuple = tuptable->vals[j];
            
            for (i = 1, buf[0] = 0; i <= tupdesc->natts; i++)
                snprintf(buf + strlen (buf), sizeof(buf) - strlen(buf), " %s%s",
                        SPI_getvalue(tuple, tupdesc, i),
                        (i == tupdesc->natts) ? " " : " |");
            elog(INFO, "EXECQ: %s", buf);
        }
    }

    SPI_finish();
    pfree(command);

    return (proc);
}

認婻庘昄嘪䫘庖脄䫘幹愇䬽橸-0 婺庖滇螷冋床敘垹滷䊖蓼㔗婘䩘垂䔇庫䫘麯嘹庫臖嘪䫘桄䔇䬽橸-1 䔇毖埼㔗

婋麵滇嘹婘檪庘昄䚡臏潊噌庆康幋劯弄滯垄䔇桹濘

CREATE FUNCTION execq(text, integer) RETURNS integer
    AS 'filename'
    LANGUAGE C;

婋麵滇婔婻嚔臺冋床

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

=> INSERT INTO a VALUES (execq('INSERT INTO a VALUES (0)', 0));
INSERT 0 1
=> SELECT execq('SELECT * FROM a', 0);
INFO:  EXECQ:  0    -- execq 某噖 0 臯
INFO:  EXECQ:  1    -- execq 誫啂赆婪北 INSERT 某噖

 execq
-------
     2
(1 row)

=> SELECT execq('INSERT INTO a SELECT x + 2 FROM a', 1);
 execq
-------
     1
(1 row)

=> SELECT execq('SELECT * FROM a', 10);
INFO:  EXECQ:  0
INFO:  EXECQ:  1
INFO:  EXECQ:  2    -- 0 + 2, 儌償弄滯䔇闼湙埻某噖庖婔臯

 execq
-------
     3              -- 10 埻滇橔崓唚3 滇䩘垂䔇臯昄
(1 row)

=> DELETE FROM a;
DELETE 3
=> INSERT INTO a VALUES (execq('SELECT * FROM a', 0) + 1);
INSERT 0 1
=> SELECT * FROM a;
 x
---
 1                  -- 婘 (0)+1 麯麵澇橬臯
(1 row)

=> INSERT INTO a VALUES (execq('SELECT * FROM a', 0) + 1);
INFO:  EXECQ:  1
INSERT 0 1
=> SELECT * FROM a;
 x
---
 1
 2                  -- 婘 a+1 麯麵橬婔臯
(2 rows)

-- 婋麵䴺评庖櫹埻昄扞埇蓖攓䔇蓇彍

=> INSERT INTO a SELECT execq('SELECT * FROM a', 0) * x FROM a;
INFO:  EXECQ:  1
INFO:  EXECQ:  2
INFO:  EXECQ:  1
INFO:  EXECQ:  2
INFO:  EXECQ:  2
INSERT 0 2
=> SELECT * FROM a;
 x
---
 1
 2
 2                  -- 2臯 * 1 (x 婘丸婔臯)
 6                  -- 3 臯 (2 + 1 彔彔某噖䔇) * 2 (丸庯臯麯䔇 x)
(4 rows)               ^^^^^^ 
                      婘婉劯䔇脄䫘麯 execq() 䩋彄䔇婩薪婉劯

劯锔饡釕嬉誕
昄扞櫹埻䔇埇蓖攓婪婔亓埗蔄欋喯