I have a SQL function (in Postgres) that I'd like to call using Diesel. I've declared it using the sql_function! macro, and I can call the function OK. But I'm not able to get the return value — it always returns 1, which I'm assuming is a row count. How can I get the actual return value?
sql_function! {
fn my_add(a: Int4, b: Int4) -> Int4;
}
let my_add_fn = my_add(2, 4);
let result = diesel::select(my_add_fn).execute(&conn).unwrap();
dbg!(&result); // This prints 1. Should be 6
When I call my_add from the Postgres CLI, it works correctly:
select my_add(2, 4);
my_add
--------
6
(1 row)
And here is the my_add function
CREATE OR REPLACE FUNCTION my_add(
a integer,
b integer
)
RETURNS integer
AS $$
BEGIN
return a + b;
END;
$$ LANGUAGE plpgsql
IMMUTABLE;
This is an old question but figured I'd post a response in case anyone else lands here.
When you call execute as you did, what you're returned is only the number of affected rows. See: getting started guide, and search for "get_result". In a select, load is probably the best choice, as a comment already noted - (docs).
To get back the result(s) from an insert or update query, replace execute with get_result or get_results for multiple rows (which will give you back a Vec<T> instead of just T) ... more docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With