为柴油“可插入”结构指定寿命参数有什么好处

时间:2019-11-02 14:13:21

标签: rust rust-diesel

从柴油.rs文档中,我看到诸如以下示例:

#[derive(Insertable)]
#[table_name="users"]
pub struct NewUser<'a> {
    pub first_name: &'a str,
    pub last_name: &'a str,
    pub email: Option<&'a str>,
 }

还有

#[derive(Insertable)]
#[table_name="posts"]
pub struct NewPost<'a> {
    pub title: &'a str,
    pub body: &'a str,
}

实际上,每个官方示例都为Insertable的参数指定了生命周期参数。但是,当我在github上阅读现实生活中的示例时,我看到的每个可插入结构都忽略了生命周期参数,而是定义了类似的结构:

#[derive(Insertable)]
#[table_name = "users"]
pub struct CreateUser {
    first_name: String,
    last_name: String,
    role: i16,
}

就数据库性能而言,一种方法是否优于另一种方法?如果我以一种或另一种方式这样做会遇到问题吗?

1 个答案:

答案 0 :(得分:1)

您所显示的示例之间的主要区别不是存在生命周期注释:在一种情况下,要插入的值归Insertable结构所有,而在另一种情况下,它们不具有

在这种情况下:

#[derive(Insertable)]
#[table_name="users"]
pub struct NewUser<'a> {
    pub first_name: &'a str,
    pub last_name: &'a str,
    pub email: Option<&'a str>,
 }

使用生命周期进行注释的要求是以下事实的结果:这些字段是字符串切片,是对某些其他结构或变量拥有的字符串的引用。 NewUser结构的持续时间不能超过拥有字符串的变量的持续时间。从本质上讲,它是这些其他变量的视图,使您可以在不创建任何数据副本的情况下将其内容插入数据库。

另一方面:

#[derive(Insertable)]
#[table_name = "users"]
pub struct CreateUser {
    first_name: String,
    last_name: String,
    role: i16,
}

此结构拥有字符串,因此不存在生命周期。

就哪种方法而言,这是最好的方法-它取决于整个程序的数据结构。如果要插入的字段已经存在于程序要维护的其他数据结构中,则使用第一种形式可能是适当的,因为这样可以避免不必要地复制值。

另一方面,程序可能没有可以保留值的单独数据结构,或者可能由于生存期问题,Insertable必须拥有要插入的值,甚至如果确实需要复制的话。