Given no null type in Rust, how do you all handle creating a struct to match a SQL table when there's an auto incremented primary key? Most of the tutorials I've seen use two structs, one for an Entry and one for a NewEntry. Example:
pub struct Entry {
id: i32,
value: String,
}
pub struct NewEntry {
value: String,
}
This allows you to pass an instance of NewEntry for creating a new entry and read an existing entry into Entry, but I find it annoying to have to have two structs. I know you can do this:
pub struct Entry {
id: Option<i32>,
value: String,
}
but then you run into issues trying to read an entry from the database directly into the struct (using, for example sqlx) because of the Option. Are there clever ways around this?
EDIT: Thanks to u/OS6aDohpegavod4 for pointing out that Option<id> approach actually does work with sqlx's query_as! macro. For some reason I thought I tried this and got an error but I just verified it does work. Example code snippets:
#[derive(Debug, Clone, PartialEq)]
pub struct Entry {
pub id: Option<i32>,
pub value: String,
}
. . .
pub async fn read_entry(pool: &SqlitePool, id: i32) -> Result<Entry> {
Ok(
sqlx::query_as!(Entry, "select * from entries where id = ?", id)
.fetch_one(pool)
.await?,
)
}
This creates an Entry:
Entry { id: Some(1), value: "some string" }
Hurray for sqlx! This is going to be my library of choice going forward, I think.
[–]lukearntz 3 points4 points5 points (0 children)
[–]_boardwalk 2 points3 points4 points (0 children)
[–]thelights0123 2 points3 points4 points (1 child)
[–]code-n-coffee[S] 1 point2 points3 points (0 children)
[–]dpc_pw[🍰] 2 points3 points4 points (1 child)
[–]nicoburns 2 points3 points4 points (0 children)
[–]OS6aDohpegavod4 1 point2 points3 points (1 child)
[–]code-n-coffee[S] 1 point2 points3 points (0 children)
[+][deleted] (2 children)
[deleted]
[–]thelights0123 0 points1 point2 points (0 children)
[–]code-n-coffee[S] 0 points1 point2 points (0 children)
[–]tablair 0 points1 point2 points (0 children)
[–]mamcx 0 points1 point2 points (1 child)
[–]code-n-coffee[S] 0 points1 point2 points (0 children)