user_0
user_0

Reputation: 3363

Call a PostgreSQL function and get result back with no loop

I have a simple rust program that interacts with a PostgreSQL database.

The actual code is:

for row in &db_client.query("select magic_value from priv.magic_value();", &[]).unwrap()
{
    magic_value = row.get("magic_value");
    println!("Magic value is = {}", magic_value);
}

And.. it works. But I don't like it: I know this function will return one and only one value.

From the example I found, for example here: https://docs.rs/postgres/latest/postgres/index.html and here: https://tms-dev-blog.com/postgresql-database-with-rust-how-to/

You always have a recordset to loop on.

Which is the clean way to call a function without looping?

Upvotes: 0

Views: 240

Answers (1)

cdhowie
cdhowie

Reputation: 169133

query returns a Result<Vec<Row>, _>. You are already unwrapping the Vec, so you can just use it directly instead of looping. By turning the Vec into an owning iterator yourself, you can even easily obtain a Row instead of a &Row.

magic_value = db_client.query("select magic_value from priv.magic_value();", &[])
    .unwrap()    // -> Vec<Row>
    .into_iter() // -> impl Iterator<Item=Row>
    .next()      // -> Option<Row>
    .unwrap()    // -> Row
    .get("magic_value");

Upvotes: 1

Related Questions