doc: How to map Payload back to struct?
gitmalong opened this issue · comments
Hi!
What is the proper way to go from select() ->Payload
to a custom struct?
I could not find any examples regarding that and the doc does also not mention it.
Thanks
I found that this works but I am not sure whether this is the best way to do so.
let selected = table("settings")
.select()
.filter("year = 2023")
.execute(&mut glue)
.await
.unwrap();
match selected {
gluesql_core::prelude::Payload::Select { labels, rows } => {
let time_zone_i = labels.iter().position(|x| x == "time_zone").unwrap();
let currency = labels.iter().position(|x| x == "currency").unwrap();
Settings {
currency: rows[0][currency].clone().into(),
time_zone: rows[0][time_zone_i].clone().into(),
}
},
_ => panic!(),
}
Try using Payload::Select
if you have a schema, or Payload::SelectMap
if you don't, to fetch rows.
My recommendation is to create a struct and implement TryFrom
for Payload
and struct
e.g) ever0de@a0ccda2#diff-6ecd13eab89cbf9d6f327f55c2a4a177059a5407406d3560a1bf07862a2b36fdR11
struct MyTable {
rows: Vec<Row>
}
impl TryFrom<Payload> for MyTable {
// ...
}
let mut payloads = glue.execute("SELECT * FROM Table;").unwrap();
let payload = payloads.remove(0);
let table: MyTable = payload.try_into().unwrap();
// ...
Thanks! How can I provoke getting a SelectMap from my select query builder?
The return values of the AstBuilder::execute
and Glue::execute
functions are similar.
- https://docs.rs/gluesql/latest/gluesql/core/ast_builder/trait.Execute.html
- https://docs.rs/gluesql/latest/gluesql/prelude/struct.Glue.html#method.execute
You can remove Vec::remove
from the above example, because you get Payload
instead of Vec<Payload>
.
Thanks for the hints. A macro like https://docs.rs/sqlx/latest/sqlx/trait.FromRow.html would be useful to derive impl TryFrom<Payload> for MyTable
for common types.