Rust newbie here (though it seems I have been a newbie for an awful long time and will continue to be! )
Using the sqlx library in Rust and PostgreSQL, I would like to perform some dynamic queries, i.e. the tables and columns and WHERE clauses will not be known until runtime.
When I use .execute
, I get back a PgQueryResult
and when I use .fetch_all
I get back a Vec<PgRow>
. But neither seems to offer a way to iterate over rows returned and then identify the columns from the response metadata and obtain the field values individually.
// Returns PgQueryResult
let result = sqlx::query("select * from category")
.execute(&pool)
.await.unwrap();
// Returns Vec<PgRow>
let results = sqlx::query("select * from category")
.fetch_all(&pool)
.await.unwrap();
There is an example pointed in the sqlx README which seems to come close:
// provides `try_next`
use futures::TryStreamExt;
let mut rows = sqlx::query("SELECT * FROM users WHERE email = ?")
.bind(email)
.fetch(&mut conn);
while let Some(row) = rows.try_next().await? {
// map the row into a user-defined domain type
let email: &str = row.try_get("email")?;
}
But this does not work for me. (There is no try_get
function).
But even this suggests that I need, at compile time, to know what the data looks like in order to map it.
Perhaps there is an example I have not seen of how to do this completely dynamically, i.e. obtain a list from the column, then obtain each field individually using that for each row.
Also, what worries me a little about that last example with the stream: does it go back to the database to fetch every row? I wouldn't want that.