0

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.

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

1 Answers1

2

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);");
pozs
  • 34,608
  • 5
  • 57
  • 63
  • I can't use the first example in pqxx v4.0.1 – FrozenHeart Aug 22 '14 at 14:16
  • It seems (the current) `libpqxx` does not handle param types at all: http://pqxx.org/development/libpqxx/browser/trunk/src/connection_base.cxx#L906 -- *If paramTypes is NULL, or any particular element in the array is zero, the server assigns a data type to the parameter symbol in the same way it would do for an untyped literal string.* http://www.postgresql.org/docs/current/static/libpq-exec.html – pozs Aug 22 '14 at 14:50