Search code examples
postgresqllibpqxx

How do I pass an array of integers to a Postgres stored procedure with pqxx?


Say I have a function:

CREATE OR REPLACE FUNCTION foo(ids integer[]) RETURNS void
    LANGUAGE plpgsql
    AS $$
BEGIN
    SELECT 1;
END;
$$;

In pqxx, what is the best way to go about invoking this? I can invoke integers and strings fine but what is the right type to pass for arrays?

conn.prepare("foo_call", "select foo($1)");

conn.prepared("foo_call")(VALUE);

Solution

  • So apparently pqxx will play nice with the array being encoded as a string. I'm not sure where the syntax for this is defined but it's:

    '{1, 22, 333}'
    
    typedef list<db_id_t> db_ids_t;
    
    string to_param_string(const db_ids_t& ids) {
        stringstream ss;
    
        bool first(true);
        for(db_ids_t::const_iterator i=ids.begin();i != ids.end();i++) {
            ss << (first ? "{" : ",") << (*i);
            first = false;
        }
    
        ss << "}";
    
        return ss.str();
    }
    

    If anyone can post an example of not having to encode it as a string I'd be happy to accept that as the answer instead.