PostgreSQL:从C函数中获取序列nextval

时间:2016-10-05 13:33:36

标签: postgresql postgresql-9.6

我写了以下内容来获取序列中的下一个值。它完美地运作:

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;
}

但是,确实有一个函数调用我无需通过SPI即可完成?

1 个答案:

答案 0 :(得分:2)

不幸的是nextval_internal未导出,但您可以尝试拨打nextval_oid。我没有测试这段代码,所以你可能需要调试它:

#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));
}

传递序列的Oid和您自己的SQL函数中的fcinfo