0

I wrote the following to fetch the next value in a sequence. It works perfectly:

static int64 _get_md_key_next_serial()
{
    int                  ret = SPI_execute("SELECT nextval('md_key_seq')", true, 1);

    if (ret <= 0)
        return (int64)ret;

    if (SPI_processed)
    {
        SPITupleTable   *tuptable = SPI_tuptable;
        bool             fieldNull;
        Datum            datum = SPI_getbinval(tuptable->vals[0], tuptable->tupdesc, 1, &fieldNull);

        if (!fieldNull)
            return DatumGetInt64(datum);
    }

    return NULL_ZERO;
}

However, surely there is a function call I can make without having to go through SPI?

1 Answer 1

2

Unfortunately nextval_internal is not exported, but you could try to call nextval_oid. I did not test this code, so you'll probably have to debug it:

#include "fmgr.h"
#include "commands/sequence.h"

static int64 nextval(Oid sequenceID, FunctionCallInfo fcinfo)
{
    FunctionCallInfoData locfcinfo;

    InitFunctionCallInfoData(locfcinfo, fcinfo->flinfo, 1,
                             InvalidOid, NULL, NULL);
    locfcinfo.arg[0] = ObjectIdGetDatum(sequenceID);
    locfcinfo.argnull[0] = false;

    return DatumGetInt64(nextval_oid(&locfcinfo));
}

Pass the Oid of the sequence and the fcinfo from your own SQL function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.