【问题标题】:Read/write large object from postgres using pqxx使用 pqxx 从 postgres 读取/写入大对象
【发布时间】:2020-11-18 09:49:48
【问题描述】:

主要的 pqxx API 使用列作为文本。那么如何使用 pqxx 库从大对象(LOB)中访问二进制数据呢?

【问题讨论】:

    标签: c++ iostream libpqxx lob largeobject


    【解决方案1】:

    有几种方法。第一种方式是将数据与 bytea 相互转换,并通过通用 pqxx api 工作。如果您知道如何使用 bytea,那么这可能就是您的方式。以下是如何将字符串插入为 lob、纯 sql、无 c++ 代码的示例:

    select lo_from_bytea(0, 'this is a test'::bytea);
    ...
    select encode(lo_get(190850), 'escape'); -- here 190850 is the oid for lob created by the first line.
    

    另一个选项是使用 pqxx 库提供的 iostream API。如何使用它的例子不多,所以我们开始吧:

    // write lob
    auto conn = std::make_shared<pqxx::connection>(url);
    auto tran = std::make_shared<pqxx::work>(*conn);
    auto stream = std::make_shared<pqxx::olostream>(*tran, oid);
    stream->write(data, size);
    stream->flush();
    stream.reset();
    tran->commit();
    
    // read lob
    stream = std::make_shared<pqxx::ilostream>(*tran, oid);
    ...
    sszie_t get_chunk(shard_ptr<> stream, char *buf, size_t max_len)
    {
        while (!stream->eof() && len < max_len && stream->get(buf[len])) {
            len++;
        }
    
        return (len > 0 || !stream->eof()) ? len : -1;
    }
    

    注意:pqxx::ilostream 中有一个bug,如果数据中的0xff 字节会碰到内部缓冲区边界,则会导致数据被截断,它会被误认为是EOF 字符。该错误已在 2020 年 2 月得到修复,目前此修复并未适用于所有发行版。

    【讨论】:

      猜你喜欢
      • 2019-09-17
      • 2022-01-13
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      相关资源
      最近更新 更多