如何通过libpq c api插入字节的数组

How to insert array of bytes in PostgreSQL table via libpq C++ API

本文关键字:字节 数组 插入 api 何通过 libpq      更新时间:2023-10-16

我正在尝试更新表

CREATE TABLE some_table
(
    id integer NOT NULL,
    client_fid bigint NOT NULL,
    index bytea[],
    update_time timestamp without time zone
)
WITH (
    OIDS = FALSE

使用从这里剪切的修改代码如何使用libpq?

以二进制格式插入文本数组?
#define BYTEAARRAYOID 1001
#define BYTEAOID 17

这是PGVALS_T结构定义

struct pgvals_t
{
    /* number of array dimensions */
    int32_t ndims;
    /* flag describing if array has NULL values */
    int32_t hasNull;
    /* Oid of data stored in array. In our case is 25 for TEXT */
    Oid oidType;
    /* Number of elements in array */
    int32_t totalLen;
    /* Not sure for this one. 
     I think it describes dimensions of elements in case of arrays storing arrays */
    int32_t subDims;
    /* Here our data begins */
} __attribute__ ((__packed__));

我已经从struct中删除了数据核指针,因为它影响了备忘录的数据布局

std::size_t nElems = _data.size();
        uint32_t valsDataSize = sizeof(prx::pgvals_t) + sizeof(int32_t) * nElems +
                            sizeof(uint8_t)*nElems;
        void *pData = malloc(valsDataSize);
        prx::pgvals_t* pvals = (prx::pgvals_t*)pData;
        /* our array has one dimension */
        pvals->ndims = ntohl(1);
        /* our array has no NULL elements */
        pvals->hasNull = ntohl(0);
        /* type of our elements is bytea */
        pvals->oidType = ntohl(BYTEAOID);
        /* our array has nElems elements */
        pvals->totalLen = ntohl(nElems);
        pvals->subDims = ntohl(1);
        int32_t elemLen = ntohl(sizeof(uint8_t));
        std::size_t offset = sizeof(elemLen) + sizeof(_data[0]);
        char * ptr = (char*)(pvals + sizeof(prx::pgvals_t));
        for(auto byte : _data){
            memcpy(ptr, &elemLen, sizeof(elemLen));
            memcpy(ptr + sizeof(elemLen), &byte, sizeof(byte));
            ptr += offset;
        }
        Oid paramTypes[] = { BYTEAARRAYOID };
        char * paramValues[] = {(char* )pData};
        int paramLengths[] =  { (int)valsDataSize };
        int paramFormats[] = {1};
        PGresult *res = PQexecParams(m_conn, _statement.c_str(),
            1,             
            paramTypes,
            paramValues,
            paramLengths,
            paramFormats,
            1
        );
        if (PQresultStatus(res) != PGRES_COMMAND_OK) {
            std::string errMsg = PQresultErrorMessage(res);
            PQclear(res);
        throw std::runtime_error(errMsg);
    }
    free(pData);

二进制数据包含在std :: vector变量中,并在a _statement 类型std :: string

中使用以下查询。
INSERT INTO some_table 
(id, client_id, "index", update_time) 
VALUES 
 (1, 2, $1, NOW())

现在致电pqexecparams后,我有一个例外,带有消息 "绑定参数1中的错误二进制数据格式"

这里有什么问题?

如果要以二进制格式传递bytea[],则必须使用array_recv读取的二进制数组格式,并由array_send编写。

您不能只通过C数组。