Home > Net >  Rust diesel conditionally update fields
Rust diesel conditionally update fields

Time:05-16

I am trying to use diesel diesel = { version = "1.4.8", features = ["postgres","64-column-tables","chrono","serde_json"] } for a project and I would like update some of the fields in postgresql table, the pass parameter from the client define like this:

pub struct UpdateChannelRequest {
    pub channelId: i64,
    pub tags: Option<Vec<Tag>>,
    pub commentRss: i32,
    pub partOutput: i32,
    pub subStatus: i32
}

I am using this code to update the table right now:

pub fn update_channel_impl(request: &Json<UpdateChannelRequest>){
    use crate::model::diesel::dolphin::dolphin_schema::rss_sub_source::dsl::*;
    let connection = config::establish_connection();
    let predicate = crate::model::diesel::dolphin::dolphin_schema::rss_sub_source::id.eq(request.channelId);
    diesel::update(rss_sub_source.filter(predicate))
        .set((comment_rss.eq(&request.commentRss),part_output.eq(&request.partOutput),sub_status.eq(&request.subStatus)))
        .get_result::<RssSubSource>(&connection)
        .expect("unable to update channel");
}

the problem I am facing is that the frontend need to pass all update fields everytime. Is it possible to make the server side conditional update with passing fields? For example, define some of the fields as Option, if passed the fields value, update it. If not pass the value, just ignore the fields(the id must be passed because we need to update the record by id).

CodePudding user response:

If the struct has any optional fields on it, these will also have special behavior. By default, #[derive(AsChangeset)] will assume that None means that you don’t wish to assign that field.

All about updates guide

  • Related