如何通过libpq C ++ API在PostgreSQL表中插入字节数组

时间:2019-02-27 19:28:26

标签: c++ postgresql libpq bytea

我正在尝试更新表格

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

使用从此处How to insert text array in PostgreSQL table in binary format using 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中删除了dataBegins指针,因为它会影响备忘录中的数据布局

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变量中,并且正在类型std :: string

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

现在,在调用PQExecParams之后,出现消息异常      “绑定参数1中的二进制数据格式不正确”

这里可能是什么问题?

1 个答案:

答案 0 :(得分:0)

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

您不能只传递C数组。