From the diesel.rs docs I am seeing examples such as:
#[derive(Insertable)]
#[table_name="users"]
pub struct NewUser<'a> {
pub first_name: &'a str,
pub last_name: &'a str,
pub email: Option<&'a str>,
}
And
#[derive(Insertable)]
#[table_name="posts"]
pub struct NewPost<'a> {
pub title: &'a str,
pub body: &'a str,
}
In fact every official example specifies a lifetime parameter for Insertable's. However, "in the wild" when I'm reading real-life examples on github every Insertable struct I am seeing omits a lifetime parameter and instead defines similar structs:
#[derive(Insertable)]
#[table_name = "users"]
pub struct CreateUser {
first_name: String,
last_name: String,
role: i16,
}
Is there a benefit to one approach over the other in terms of database performance? Can I run into problems if I do it one way or the other?
The key difference between the examples you have shown is not that there is a lifetime annotation: it is that in one case, the values to be inserted are owned by the Insertable
structure while in the other they are not.
In this case:
#[derive(Insertable)]
#[table_name="users"]
pub struct NewUser<'a> {
pub first_name: &'a str,
pub last_name: &'a str,
pub email: Option<&'a str>,
}
the requirement to annotate with a lifetime is a consequence of the fact that the fields are string slices, which are references to strings that are owned by some other structure or variable. The NewUser
struct cannot last any longer than the variable(s) that do own the strings. It is essentially a view of these other variables, which allows you to insert their contents into the database without making any copies of the data.
On the other hand:
#[derive(Insertable)]
#[table_name = "users"]
pub struct CreateUser {
first_name: String,
last_name: String,
role: i16,
}
This structure owns the strings, so lifetimes do not come into it.
In terms of which would be the best approach - it depends on the data structures of the whole program. If the fields to be inserted already exist in other data structures that the program is maintaining, then it might be appropriate to use the first form as you could avoid making unnecessary copies of the values.
On the other hand perhaps the program does not have any separate data structure in which it can keep the values, or perhaps lifetime issues make it necessary for the Insertable
to own the values that are to be inserted, even if that does make a copy necessary.