C Set Returning Function (SRF)
C Set Returning Function (SRF)
От:
Gary Chambers <gwchamb@gwcmail.com>
Дата:
All,
I'm trying to write a simple set returning function that links the GNU pwgen
code. I can't seem to pull it together to return the results reliably.
There are several examples that demonstrate returning tuples, but I can't
seem to find any examples of SRFs returning single (specifically textual)
types. Will someone please offer some insight?
#include "postgres.h"
#include "utils/builtins.h"
#include "fmgr.h"
#include "funcapi.h"
#include
#include "pwgen.h"
PG_MODULE_MAGIC;
int (*pw_number)(int max_num);
PG_FUNCTION_INFO_V1(pwgen_srf);
Datum
pwgen_srf(PG_FUNCTION_ARGS)
{
FuncCallContext *funcctx;
int pwgen_flags = PW_DIGITS | PW_UPPERS;
int call_cntr, max_calls, pw_length;
if (SRF_IS_FIRSTCALL()) {
MemoryContext oldcontext;
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
funcctx->max_calls = PG_GETARG_UINT32(0);
MemoryContextSwitchTo(oldcontext);
}
funcctx = SRF_PERCALL_SETUP();
pw_length = PG_GETARG_INT32(1);
call_cntr = funcctx->call_cntr;
max_calls = funcctx->max_calls;
pw_number = pw_random_number;
if (call_cntr < max_calls) {
char *pw;
pw = (char *)palloc(pw_length);
pw_phonemes(pw, pw_length, pwgen_flags);
SRF_RETURN_NEXT(funcctx, CStringGetDatum(pw));
} else {
SRF_RETURN_DONE(funcctx);
}
}
Thank you!
-- Gary Chambers
Re: C Set Returning Function (SRF)
От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Gary Chambers writes: > I'm trying to write a simple set returning function that links the GNU pwgen > code. I can't seem to pull it together to return the results reliably. > There are several examples that demonstrate returning tuples, but I can't > seem to find any examples of SRFs returning single (specifically textual) > types. Will someone please offer some insight? I think the problem is here: > SRF_RETURN_NEXT(funcctx, CStringGetDatum(pw)); CStringGetDatum produces a datum of type cstring. You want a datum of type text. PointerGetDatum(cstring_to_text(pw)) ought to do it. regards, tom lane
Re: C Set Returning Function (SRF)
От:
Gary Chambers <gwchamb@gwcmail.com>
Дата:
Tom, > CStringGetDatum produces a datum of type cstring. You want a datum of > type text. PointerGetDatum(cstring_to_text(pw)) ought to do it. Thanks very much -- that works! This is my first foray into writing C functions so I have a lot to learn. Is there a better way to accomplish what I am trying to do? -- Gary Chambers