当使用与 tokio-diesel 关联时,“参数要求为 `'static` 借用 `record`”

Posted

技术标签:

【中文标题】当使用与 tokio-diesel 关联时,“参数要求为 `\'static` 借用 `record`”【英文标题】:"argument requires that `record` is borrowed for `'static`" when using belonging_to associations with tokio-diesel当使用与 tokio-diesel 关联时,“参数要求为 `'static` 借用 `record`” 【发布时间】:2020-11-25 03:13:01 【问题描述】:

我正在尝试使用 Tokio-Diesel 将 async/await 与我的 ORM 一起使用。我无法使用 Diesel 的 belonging_to 关联,因为它抱怨我需要静态生命周期。我已经尝试过异步块,但没有任何改变生命周期错误。

Cargo.toml

[package]
name = "tokio_diesel"
version = "0.1.0"
authors = ["servonlewis"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
diesel =  version = "1.4.3", features = ["postgres", "r2d2", "serde_json", "chrono", "uuid"] 
r2d2 = "0.8.8"
tokio =  version = "0.2", features = ["full"] 
tokio-diesel = "0.3.0"
uuid =  version = "0.6.5", features = ["serde", "v4"] 

ma​​in.rs

#[macro_use]
extern crate diesel;
use diesel::prelude::*;
use tokio_diesel::*;

table! 
    articles (id) 
        id -> Integer,
        title -> Text,
    


table! 
    articles_visible_to_groups (id) 
        id -> Integer,
        article_id -> Integer,
        groups_id -> Integer,
    


table! 
    groups (id) 
        id -> Integer,
        name -> Varchar,
    


joinable!(articles_visible_to_groups -> articles (article_id));
joinable!(articles_visible_to_groups -> groups (groups_id));

allow_tables_to_appear_in_same_query!(articles, articles_visible_to_groups, groups,);

use crate::articles::dsl::*;
use crate::groups::dsl::*;
use diesel::pg::PgConnection;
use diesel::r2d2::ConnectionManager, Pool;

pub type PostgresPool = Pool<ConnectionManager<PgConnection>>;

pub fn get_pool() -> PostgresPool 
    let url = "postgres://actix:actix@localhost:5432/actix".to_string();
    let mgr = ConnectionManager::<PgConnection>::new(url);
    r2d2::Pool::builder()
        .build(mgr)
        .expect("could not build connection pool")


#[derive(Queryable, Identifiable, Associations, Debug)]
#[table_name = "articles"]
pub struct Article 
    pub id: i32,
    pub title: String,


#[derive(Identifiable, Queryable, Associations, Debug, PartialEq)]
#[belongs_to(Group, foreign_key = "groups_id")]
#[belongs_to(Article)]
#[table_name = "articles_visible_to_groups"]
pub struct ArticleVisibleToGroup 
    pub id: i32,
    pub article_id: i32,
    pub groups_id: i32,


#[derive(Queryable, Identifiable, Associations, Debug, PartialEq)]
pub struct Group 
    pub id: i32,
    pub name: String,


pub async fn groups_who_can_see(conn: &PostgresPool, an_id: i32) -> Vec<Group> 
    use diesel::pg::expression::dsl::any;

    let record = articles
        .find(an_id)
        .load_async::<Article>(conn)
        .await
        .unwrap();

    let list = ArticleVisibleToGroup::belonging_to(&record)
        .select(articles_visible_to_groups::groups_id)
        .load_async::<i32>(conn)
        .await
        .unwrap();

    groups
        .filter(groups::id.eq_all(any(list)))
        .load_async::<Group>(conn)
        .await
        .unwrap()


#[tokio::main]
async fn main() 
    println!("Hello, world!");
    // pool.get_ref().to_owned(),

    let pool = get_pool();
    let res = groups_who_can_see(&pool, 1).await;

    println!(":#?", res);

error[E0597]: `record` does not live long enough
  --> src/main.rs:80:52
   |
80 |     let list = ArticleVisibleToGroup::belonging_to(&record)
   |                ------------------------------------^^^^^^^-
   |                |                                   |
   |                |                                   borrowed value does not live long enough
   |                argument requires that `record` is borrowed for `'static`
...
91 | 
   | - `record` dropped here while still borrowed

【问题讨论】:

很确定这将是a limitation of tokio-diesel,其中有一些'static 边界。 你能解释一下吗? 我想知道我是否应该对这些属于函数的函数使用阻塞代码,而让其余函数异步。会很奇怪,但我有选择吗? 我确实看到属于要求“父级”但 Tokio-diesel 返回“静态结果”。我想我可能需要尝试其他方法? 【参考方案1】:

看起来我可以通过不使用 belongs_to 而是使用过滤器来解决这个问题。

这个例子是异步工作的,而不是上面的例子。

    pub async fn groups_who_can_see(
        conn: &PostgresPool,
        an_id: String,
    ) -> FieldResult<Vec<Group>> 
        use diesel::pg::expression::dsl::any;
        let my_id = uuid::Uuid::parse_str(&an_id)?;

        let list = articles_visible_to_groups
            .filter(article_id.eq_all(my_id))
            .select(articles_visible_to_groups::groups_id)
            .load_async::<uuid::Uuid>(&conn)
            .await?;

        let data = groups
            .filter(groups::id.eq_all(any(list)))
            .load_async::<Group>(&conn)
            .await;

        graphql_translate(data)
    

【讨论】:

以上是关于当使用与 tokio-diesel 关联时,“参数要求为 `'static` 借用 `record`”的主要内容,如果未能解决你的问题,请参考以下文章

当类型是关联类型时,无法将类型的值转换为预期的参数类型

为啥使用mklink 做目录关联时,提示“当文件已存在时,无法创建该文件”

关联与依赖的区别

Drupal 视图 - 使用 CCK、NodeReference 和参数将 1 个节点与 N 个其他节点相关联

当与查询参数关联的转换/验证失败时执行重定向

当 UIPickerView 与 TextField 的 inputView 关联时,如何重置它?