【问题标题】:More generic CRUD. RUST, Diesel更通用的 CRUD。生锈,柴油
【发布时间】:2022-12-10 10:19:31
【问题描述】:

是否可以使用柴油创建更通用的查询? 我知道如何为每个属性创建更新或删除。但我的观点是为许多结构创建通用更新。 我的模特:

#[derive(Associations, Identifiable, Queryable, PartialEq, Debug)]
#[diesel(belongs_to(User))]
#[diesel(table_name = books)]
pub struct Book {
    pub id: i32,
    pub user_id: i32,
    pub title: String,
    pub body: String,
    pub book_description: String,
    pub book_image: Option<String>,
    pub publish_day: chrono::NaiveDateTime,
}

#[derive(Associations, Identifiable, Queryable, PartialEq, Debug)]
#[diesel(belongs_to(Book))]
#[diesel(table_name = book_comments)]
pub struct BookComment {
    pub id: i32,
    pub book_id: i32,
    pub body: String,    
    pub publish_day: chrono::NaiveDateTime,
} 

我的模式:

diesel::table! {
    books (id) {
        id -> Int4,
        user_id -> Int4,
        title -> Varchar,
        body -> Text,
        book_description -> Varchar,
        book_image -> Nullable<Varchar>,
        publish_day -> Timestamp,
    }
}

diesel::table! {
    book_comments (id) {
        id -> Int4,
        book_id -> Int4,
        body -> Varchar,
        publish_day -> Timestamp,
    }
}


工作版本:

pub fn upate<T>(&mut self, book_id: &i32, title: &str) -> Book {
        let result = diesel::update(books::table)
            .filter(book::id.eq(&book_id))
            .set(book::title.eq(title))
            .get_result::<Book>(&mut self.connection)
            .expect("Failed to update book");

        result
    }
   

我正在尝试这样的事情:

 pub fn upate<T, U, P: Table, S>(&mut self, find_by: &T, change: U, target_table: Table,change_param: &S) -> Book {
        let result = diesel::update(target_table)
            .filter(find_by.eq(&book_id))
            .set(S.eq(change))
            .get_result::<U>(&mut self.connection)
            .expect("Failed to update book");

        result

但是当然不行。这可能吗?

对解决方案帮助不大。

【问题讨论】:

标签: postgresql rust orm rust-diesel


【解决方案1】:

我使用宏完成了此操作,这是我使用的代码中的 sn-p

#[macro_export]
macro_rules! get_by_id {
    ($table:ident,$m:ident,$pool:ident,$id:ident) => {
         {
            let conn = $pool.get()?;
            let res = $table::table
                .filter($table::columns::id.eq($id))
                .get_result::<$m>(&conn)?;
            Ok(res) as Result<$m, Error>
        }
    };
}

编辑:可以这样使用:

let user = get_by_id!(schema::users, User, pool, user_id)?;

【讨论】:

  • 你能提供这个宏的用法吗? get_by_id!(模式::用户::id,用户)?是这样的吗?
  • 我也试过:get_by_id!(user_table, User, get_by_id(connection, user_id));我不知道如何使用包含参数的函数调用宏。
  • @RfDzDeveloper 我更改了代码,使其不包含函数,使用该函数意味着您必须在单独的模块中定义它。现在它没有功能所以你可以直接使用示例用法中写的宏
猜你喜欢
  • 2021-03-17
  • 2022-12-09
  • 2022-07-08
  • 2022-01-15
  • 2022-12-10
  • 2022-01-20
  • 2022-01-05
  • 2020-02-06
  • 2021-11-08
相关资源
最近更新 更多