Search code examples
c++postgresqlstored-procedureslibpqxx

How to call overloaded remote procedure from pqxx


How to call overloaded remote procedure from pqxx?

Procedures eg:

CREATE OR REPLACE FUNCTION foo(str text) RETURNS text AS $$
BEGIN    
    RETURN 'text';
END;
$$ LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION foo(num integer) RETURNS text AS $$
BEGIN    
    RETURN 'int';
END;
$$ LANGUAGE plpgsql;

C++ code:

pqxx::connection connection(/* credentials */);

std::string query_mark = "test_procedure_mark";
connection.prepare(query_mark, "SELECT foo($1);");

//first case
pqxx::work work(connection);
pqxx::result res = work.prepared(query_mark)("text").exec();
work.commit();
std::string ans = res[0][0].as(std::string(""));  //ans here "text"

//second case
pqxx::work work(connection);
pqxx::result res = work.prepared(query_mark)(1).exec();
work.commit();
std::string ans = res[0][0].as(std::string("")); //ans here "text"

How can i call "foo(num integer)" from c++ code? In example desired result "int" in "ans".

psql.exe output:

SELECT foo(1); returns "int"

SELECT foo("test"); returns "text"

Thanks in advance.


Solution

  • I don't think you can solve it with a single prepared statement.

    You can set each parameter's treatment in libpqxx 3.1 (see third example), like:

    connection.prepare(query_mark_text, "SELECT foo($1);")("text", pqxx::prepare::treat_string);
    connection.prepare(query_mark_int,  "SELECT foo($1);")("integer");
    

    But i cannot see that in the latest docs.

    Or, you can cast your parameteres to the desired type on PostgreSQL's side, with:

    connection.prepare(query_mark_text, "SELECT foo($1::text);");
    connection.prepare(query_mark_int,  "SELECT foo($1::int);");