在 PostgreSQL 上,我在 C 中实现了以下存储过程:
extern "C" DLLEXPORT Datum
selectServeralRows(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
int call_cntr;
int max_calls;
TupleDesc tupdesc;
AttInMetadata *attinmeta;
/* stuff done only on the first call of the function */
if (SRF_IS_FIRSTCALL())
{
MemoryContext oldcontext;
/* create a function context for cross-call persistence */
funcctx = SRF_FIRSTCALL_INIT();
/* switch to memory context appropriate for multiple function calls */
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* total number of tuples to be returned */
funcctx->max_calls = 1;
/* Build a tuple descriptor for our result type */
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("function returning record called in context "
"that cannot accept type record")));
/*
* generate attribute metadata needed later to produce tuples from raw
* C strings
*/
attinmeta = TupleDescGetAttInMetadata(tupdesc);
funcctx->attinmeta = attinmeta;
MemoryContextSwitchTo(oldcontext);
}
/* stuff done on every call of the function */
funcctx = SRF_PERCALL_SETUP();
if (funcctx->call_cntr < funcctx->max_calls) /* do when there is more left to send */
{
Datum* val = (Datum*)palloc(2 * sizeof(Datum));
HeapTuple tuple;
Datum result;
bool nulls[2]={false,false};
char * n = new char[2];
n[0] = '1';
n[1] = '\0';
char * m = new char[2];
m[0] = '2';
n[1] = '\0';
val[0] = CStringGetTextDatum(m);
val[1] = CStringGetTextDatum(n);
/* build a tuple */
tuple = heap_form_tuple(tupdesc, val, nulls);
/* make the tuple into a datum */
result = TupleGetDatum(funcctx->slot, tuple);
/* clean up (this is not really necessary) */
SRF_RETURN_NEXT(funcctx, result);
}
else
SRF_RETURN_DONE(funcctx);
}
代码几乎和这里一样:http ://www.postgresql.org/docs/8.4/static/xfunc-c.html
如果该过程只返回一行,那么一切都很好,并且只有一行的表是所需的。但是如果这样改变一行
/* total number of tuples to be returned */
funcctx->max_calls = 2;
查询的执行因以下消息而崩溃:
程序收到信号 EXC_BAD_ACCESS,无法访问内存。原因:KERN_INVALID_ADDRESS at address: 0x000000000000041a 0x0000000100002d8b in heap_form_tuple()
单步执行代码显示在崩溃之前什么都不是无效指针,所以我有点无能为力。还有什么我监督的吗?
编辑:该函数在 psql 中是这样调用的:
select (selectServeralRows()).*
编辑:函数的 SQL 定义:
CREATE OR REPLACE FUNCTION selectServeralRows()
RETURNS TABLE(k character varying(20), j character varying(20)) AS
'/opt/local/lib/postgresql84/Debug/libSeveralRows', 'selectServeralRows'
LANGUAGE c STABLE STRICT;