taocpp / taopq

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

Support arrays (as parameters and as fields) #28

Closed bog-dan-ro closed 3 years ago

bog-dan-ro commented 4 years ago

Will be great if we could write something like:

conn->execute( "CREATE TABLE example ( tarray TEXT[] NOT NULL )" );
std::vector<std::string> args{"1", "2", "val3"};
conn->execute( "INSERT INTO  example (tarray) VALUES($1) ", args);
conn->execute( "INSERT INTO  example (tarray) VALUES($1) ", {"a", "b", "c"});

auto res = conn->execute( "SELECT tarray FROM example");
for (const auto &row : res) {
   for (const auto &val : row[0].as<std::vector<std::string>>()) 
    std::cout << val << std::endl;
}

/// multidimensional arrays will be even better
conn->execute( "CREATE TABLE examplem ( tarray TEXT[][] NOT NULL )" );
std::vector<std::vector<std::string>> args{{"1", "2", "3"}. {"4", "5"}};
conn->execute( "INSERT INTO  examplem (tarray) VALUES($1) ", args);
conn->execute( "INSERT INTO  examplem (tarray) VALUES($1) ", {{"a1", "b1", "c1"}, {"a2", "b2"});

auto res = conn->execute( "SELECT tarray FROM examplem");
for (const auto &row : res) {
   for (const auto &array : row[0].as<tao::pq::array_field>()) 
     for (const auto &val : array.as<std::vector<std::string>>()) 
        std::cout << val << std::endl;
}
lacasaprivata2 commented 3 years ago

+1

d-frey commented 3 years ago

Support for array on the API level (libpq) is just terrible. It's hard to understand why they have almost no support for sending and receiving arrays properly, i.e. without escaping and unescaping your data over and over again, manually. Not to mention the total lack of documentation on how to send or receive it in binary mode. sigh

Anyways, I started working on this, but consider it work-in-progress for now. Anything might change still and I reserve the right to simply remove all of the array support if things get out of hand.

d-frey commented 3 years ago

BTW: The example seems slightly flawed, as I get:

exception: PGRES_FATAL_ERROR/22P02: ERROR:  malformed array literal: "{{1,2,3},{4,5}}"
DETAIL:  Multidimensional arrays must have sub-arrays with matching dimensions.
d-frey commented 3 years ago

We now have support for ARRAYs, so I'll close this issue. Please test and let me know if there are any problems or if you have any other feedback.