Diesel conditional query

Hi,

I need a conditional query using diesel. I have a repo function which interacts with database for querying.

I have a, b, c, d tables. I am going to run a query for a and use left_joins to join b, c and d to a. Here is the important part: I need to run those left_joins by looking some filters (is_b_active, is_c_active, is_d_active). It should run b's left_join if is_b_active is true. I did something like this:

Even though I use into_boxed() method and add left_joins using if-else cases, at the end, I am going to need to use select and load methods which both requires types inside of a tuple.

So I am a bit confused here. Is there anyone can help me?

Edit: I added a simple code below:

Filters {
    b: bool,
    c: bool,
    d: bool,
}

async fn get(
    pool: &DbPool,
    filters: Filters,
    a_id: Uuid,
) -> Result<_, DbErro> {
    let conn = util::db::get_connection(pool).await?;
    
    let res conn
        .interact(move |c| -> Result<_, DbError> { // I need to return a Result here
            let a = dsl::a::table
                .filter(dsl::a::id.eq(a_id))
                .first::<A>(c)?;

            let mut query = dsl::a::table.into_boxed();

            if filters.b {
                query = query
                    .left_join(dsl::b::table.on(dsl::b::a_id.eq(dsl::a::id)))
            }

            if filters.c {
                query = query
                    .left_join(dsl::c::table.on(dsl::c::a_id.eq(dsl::a::id)))
            }

            if filters.d {
                query = query
                    .left_join(dsl::d::table.on(dsl::d::a_id.eq(dsl::a::id)))
            }

            query = query.filter(dsl::a::id.eq(a_id));

            // After this part, I'm not sure how to handle the query result.


            query
                .select() // I don't know how to handle this
                .load::<()>(c) // I also don't know how to handle this

            Ok((a, query))
        })
}

It's not supported by diesel to conditionally modify the from clause. That's a restriction as diesel needs to know that information at compile time to check whether the later provided select/filter statements are valid for the given from clause.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.