taocpp / taopq

C++ client library for PostgreSQL
Boost Software License 1.0
265 stars 40 forks source link

Fix table writer with column type BYTEA #51

Closed skaae closed 2 years ago

skaae commented 2 years ago

Fixes #50
Add double backlash to escape the hex sequence and fixed what is think was a bug in the hex index calculations? Before the changes postgres did not interpret the hex-sequence as bytes so it would write the literal hex sequence to the database.

Before changing the following code gave different results when using INSERT vs COPY, after the path the output is the same.

    auto conn = create_db_conn()
    conn->execute("DROP TABLE IF EXISTS test_table;");
    conn->execute("CREATE TABLE test_table (  buffer_bytes BYTEA NOT NULL);");

    const unsigned char bdata[] = { 'v', 255, 0, 'a', 1, 'b', 0 };

    conn->execute( "INSERT INTO test_table VALUES ( $1 )", tao::pq::to_binary_view(bdata) );

    tao::pq::table_writer tw(conn->direct(), "COPY test_table ( buffer_bytes ) FROM STDIN");
    tw.insert(tao::pq::to_binary_view(bdata));   
    tw.commit();

    const auto result_0 = conn->execute( "SELECT * FROM test_table" )[ 0 ][ 0 ].as< std::basic_string<unsigned char > >();
    const auto result_1 = conn->execute( "SELECT * FROM test_table" )[ 1 ][ 0 ].as< std::basic_string<unsigned char > >();
    fmt::print("result_0 = {}\n", fmt::join(result_0, ", ")); // result_0 = 118, 255, 0, 97, 1, 98, 0
    fmt::print("result_1 = {}\n", fmt::join(result_1, ", ")); // result_1 = 125, 48, 48, 48, 48, 54, 55, 48, 49, 54, 56, 48, 48
skaae commented 2 years ago

I think the modolus can be replaced with

data[ pos++ ] = hex[ c & 15];
d-frey commented 2 years ago

Thank you!