PostgreSQL Programmer's Guide
PrevChapter 13. Server Programming InterfaceNext

Examples例

この SPI 使用例は、可視性規則のデモです。 もっと複雑な例が src/test/regress/regress.c と contrib/spi にあります。

これは非常に単純な SPI の使用例です。 手続き execq の最初の引数は SQL の問い合わせで、二番目は tcount です。 execq は SPI_exec を使って問い合わせを実行し、問い合わせの対象となった タプルの数を返します:

#include "executor/spi.h"	/* this is what you need to work with
SPI SPI を使うためにはこれが必要*/

int execq(text *sql, int cnt);

int
execq(text *sql, int cnt)
{
	int ret;
	int proc = 0;
	
	SPI_connect();
	
	ret = SPI_exec(textout(sql), cnt);
	
	proc = SPI_processed;
	/*
         * もしこれが SELECT で、タプルが取得されたなら、
	 * elog(NOTICE)を使って呼出元にタプルを返す
	 */
	if ( ret == SPI_OK_SELECT && SPI_processed > 0 )
	{
		TupleDesc tupdesc = SPI_tuptable->tupdesc;
		SPITupleTable *tuptable = SPI_tuptable;
		char buf[8192];
		int i;
		
		for (ret = 0; ret < proc; ret++)
		{
			HeapTuple tuple = tuptable->vals[ret];
			
			for (i = 1, buf[0] = 0; i <= tupdesc->natts; i++)
				sprintf(buf + strlen (buf), " %s%s",
					SPI_getvalue(tuple, tupdesc, i),
					(i == tupdesc->natts) ? " " : " |");
			elog (NOTICE, "EXECQ: %s", buf);
		}
	}

	SPI_finish();

	return (proc);
}

ここで、関数をコンパイルし、登録する:

create function execq (text, int4) returns int4 as '...path_to_so' language 'c';
vac=> select execq('create table a (x int4)', 0);
execq
-----
    0
(1 row)

vac=> insert into a values (execq('insert into a values (0)',0));
INSERT 167631 1
vac=> select execq('select * from a',0);
NOTICE:EXECQ:  0 <<< inserted by execq

NOTICE:EXECQ:  1 <<< value returned by execq and inserted by upper INSERT

execq
-----
    2
(1 row)

vac=> select execq('insert into a select x + 2 from a',1);
execq
-----
    1
(1 row)

vac=> select execq('select * from a', 10);
NOTICE:EXECQ:  0 

NOTICE:EXECQ:  1 

NOTICE:EXECQ:  2 <<< 0 + 2, only one tuple inserted - as specified

execq
-----
    3            <<< 10 is max value only, 3 is real # of tuples
(1 row)

vac=> delete from a;
DELETE 3
vac=> insert into a values (execq('select * from a', 0) + 1);
INSERT 167712 1
vac=> select * from a;
x
-
1                <<< no tuples in a (0) + 1
(1 row)

vac=> insert into a values (execq('select * from a', 0) + 1);
NOTICE:EXECQ:  0 
INSERT 167713 1
vac=> select * from a;
x
-
1
2                <<< これは、a + 1 のタプル
(2 rows)

--   データ変更可視性規則のデモ:

vac=> insert into a select execq('select * from a', 0) * x from a;
NOTICE:EXECQ:  1 
NOTICE:EXECQ:  2 
NOTICE:EXECQ:  1 
NOTICE:EXECQ:  2 
NOTICE:EXECQ:  2 
INSERT 0 2
vac=> select * from a;
x
-
1
2
2                <<< 2 tuples * 1 (x in first tuple)
6                <<< 3 tuples (2 + 1 just inserted) * 2 (x in second tuple)
(4 rows)             ^^^^^^^^ 
 		異る場所で起動された execq() にはタプルが見える


PrevHomeNext
Visibility of Data Changes データ変更の可視性UpFunctions