Error when defining a set returning function - Mailing list pgsql-hackers

From Esteban Zimanyi
Subject Error when defining a set returning function
Date
Msg-id CAPqRbE6ZKZ4UfAfGL5WHj6Z3Whx7QRoiYScHT8hv2Ks3LLhPQQ@mail.gmail.com
Whole thread Raw
Responses Re: Error when defining a set returning function  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-hackers
Dear all

Since I was receiving an error when defining a set returning function, I borrowed a function from PostgreSQL as follows

/* C definition */
typedef struct testState
{
  int current;
  int finish;
  int step;
} testState;

/**
* test_srf(startval int, endval int, step int)
*/
PG_FUNCTION_INFO_V1(test_srf);
Datum test_srf(PG_FUNCTION_ARGS)
{
  FuncCallContext *funcctx;
  testState *fctx;
  int result; /* the actual return value */

  if (SRF_IS_FIRSTCALL())
  {
    /* Get input values */
    int start = PG_GETARG_INT32(0);
    int finish = PG_GETARG_INT32(1);
    int step = PG_GETARG_INT32(2);
    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);

    /* quick opt-out if we get nonsensical inputs  */
    if (step <= 0 || start == finish)
    {
      funcctx = SRF_PERCALL_SETUP();
      SRF_RETURN_DONE(funcctx);
    }

    /* allocate memory for function context */
    fctx = (testState *) palloc0(sizeof(testState));
    fctx->current = start;
    fctx->finish = finish;
    fctx->step = step;
   
    funcctx->user_fctx = fctx;
    MemoryContextSwitchTo(oldcontext);
  }

  /* stuff done on every call of the function */
  funcctx = SRF_PERCALL_SETUP();

  /* get state */
  fctx = funcctx->user_fctx;

  result = fctx->current;
  fctx->current += fctx->step;
  /* Stop when we have generated all values */
  if (fctx->current > fctx->finish)
  {
    SRF_RETURN_DONE(funcctx);
  }

  SRF_RETURN_NEXT(funcctx, Int32GetDatum(result));
}

/* SQL definition */
CREATE OR REPLACE FUNCTION testSRF(startval int, endval int, step int)
  RETURNS SETOF integer
  AS 'MODULE_PATHNAME', 'test_srf'
  LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

When I execute this function I obtain

select testSRF(1,10, 2);
ERROR:  unrecognized table-function returnMode: 257

select version();
 PostgreSQL 13.2 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, 64-bit

Any idea what could be wrong ?

Thanks for your help

Esteban


pgsql-hackers by date:

Previous
From: Tatsuo Ishii
Date:
Subject: Re: Retry in pgbench
Next
From: Tom Lane
Date:
Subject: Re: Bogus collation version recording in recordMultipleDependencies