如何从pqxx调用重载的远程过程

时间:2014-08-22 13:40:25

标签: c++ postgresql stored-procedures libpqxx

如何从pqxx调用重载的远程过程?

程序例如:

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 ++代码:

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"

我如何调用" foo(num integer)"从c ++代码?在示例中期望的结果" int"在" ans"。

psql.exe输出:

  

SELECT foo(1);返回" int"

     

SELECT foo(" test");返回"文字"

提前致谢。

1 个答案:

答案 0 :(得分:1)

我认为你不能用一份准备好的陈述来解决它。

您可以在libpqxx 3.1中设置每个参数的处理(参见third example),如:

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

但我在latest docs中看不到。

或者,您可以在PostgreSQL的一侧将参数转换为所需的类型,并使用:

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