C Set Returning Function (SRF) - Mailing list pgsql-novice

From Gary Chambers
Subject C Set Returning Function (SRF)
Date
Msg-id alpine.DEB.2.00.1109072215090.2686@localhost6.localdomain6
Whole thread Raw
Responses Re: C Set Returning Function (SRF)  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-novice
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 <string.h>

#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

pgsql-novice by date:

Previous
From: Eric Hulburd
Date:
Subject: copy- what's my root directory?
Next
From: Tom Lane
Date:
Subject: Re: C Set Returning Function (SRF)