-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
What's the correct way to get owned data out of the db #18
Comments
Yes, what you need to do is to define your own struct with the data that you need and then #[derive(FromDummy)]
struct PlayerInfo {
name: String,
score: i64,
}
let player = txn.query_one(schema::Player::unique(player_id)).map(|row| {
txn.query_one(PlayerInfoDummy {
name: row.name(),
score: row.score(),
})
}); If you often need to retrieve this same data from different queries then you can make a function to do this job: impl PlayerInfo {
fn from_db<'a, 'x>(
col: impl IntoColumn<'a, schema::Schema, Typ = schema::Player>,
) -> impl Dummy<'a, 'x, schema::Schema, Out = PlayerInfo> {
let col = col.into_column();
PlayerInfoDummy {
name: col.name(),
score: col.score(),
}
}
}
let player = txn
.query_one(schema::Player::unique(player_id))
.map(|row| txn.query_one(PlayerInfo::from_db(row)));
let all_players = txn.query(|rows| {
let player = schema::Player::join(rows);
rows.into_vec(PlayerInfo::from_db(player))
}); Sadly this requires some ugly trait bounds, and the
I have thought about adding this feature. It would indeed be quite useful for smaller tables. The only downside is that it could be slow when tables get big. Also, if this feature is added then I can not deny that rust-query is in fact also an ORM haha. |
Thanks for these examples. Maybe you can add these to the docs. Could you elaborate on the fact that I have to use two times
Yeah, I get your point. Maybe it can be opted in by a feature. |
The problem is that the unique constraint does not guarantee that a matching row exists. It can only guarantee that there is at most one. This is the reason that I currently don't have a way to I really want to add a let player = txn
.query_one(schema::Player::unique(player_id).map(PlayerInfo::from_db)); |
I added a new experimental API for handling optional rows example
Sadly it does not yet allow you to map to an optional |
@teamplayer3 Stuff can still change, but please take a look at the new example: https://github.com/LHolten/rust-query/blob/5be1ef4c1f6c6f314648f78e81763086a74f3380/examples/query_optional.rs . It does the same query in 3 different ways and derives the column selection etc. |
I try to get owned data from my db:
How to do this? Do I have to create a new user struct and map the resulting row somehow on to this struct? Is it possible to reuse the schema, def to return an owned player data? Do I have to use the dummy data type?
The text was updated successfully, but these errors were encountered: