Reduce duplication in match branches - trying to be more DRY

I'd like to clean the match branches of this code up because they seem very verbose and have a lot of duplication between them, but I can't figure out how to make the compiler not complain. Any ideas or am I stuck?

    let mut pool = &context.pool;
    let name = food_input.name;
    let food = match &food_input.id {

        Some(id)=>{
            let the_id = Uuid::parse_str(&id)?;
            sqlx::query_as!(
                Food,
                r#"
                    INSERT INTO foods ( id, name )
                    VALUES ( $1, $2 )
                    RETURNING id, name, food_group_id
                "#,
                the_id,
                name
            ).fetch_one(&mut pool).await?
        }
        None=>{
            sqlx::query_as!(
                Food,
                r#"
                    INSERT INTO foods ( name )
                    VALUES ( $1 )
                    RETURNING id, name, food_group_id
                "#,
                
                name
            ).fetch_one(&mut pool).await?
        }
    };

If the macros return different types, it may be tough. If there's a common trait that provides fetch_one, you could box the result of the macro, and return that from the match arms with an explicit type of Box<dyn Trait>.

I'd be more specific, but typing code on my phone is cumbersome.

Thank you, @cliff! I was thinking I might have a chance with box dyn, I will see if I can get it working today.

I wish there were some examples/best-practices regarding db query composition with sqlx/other-Postgres-rust-client, especially with conditional stuff like this where the majority of the query is exactly the same except different/additional query args or where clauses. I like how you have to be explicit with certain things in rust like types and lifetimes, especially given the example, but composition of queries always seems so verbose/single-purpose when I implement so it makes me think there has to be a better way.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.