kurtbuilds / ormlite

An ORM in Rust for developers that love SQL.
https://crates.io/crates/ormlite
MIT License
216 stars 11 forks source link

add `where_bind_option` support #34

Closed holmofy closed 10 months ago

holmofy commented 10 months ago

I encountered an unpleasant situation while using it.

pub async fn find_by_query(
    db: &PgPool,
    query: &TemplateQuery,
    page: &PageRequest,
) -> Result<Vec<TaskTemplate>> {
    let mut query_builder = TaskTemplate::select();
    if let Some(name) = &query.name {
        query_builder = query_builder.where_bind("name like '%?'", name);
    }
    if let Some(topic) = &query.topic {
        query_builder = query_builder.where_bind("topic=?", topic);
    }
    if let Some(edition) = &query.edition {
        query_builder = query_builder.where_bind("edition=?", edition);
    }
    query_builder
        .offset(page.offset())
        .limit(page.limit())
        .fetch_all(db)
        .await
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TemplateQuery {
    name: Option<String>,
    topic: Option<TemplateTopic>,
    edition: Option<ProductEdition>,
}

If there is where_bind_option(clause: &'static str, value: Option<T>),it will be much more comfortable.

pub async fn find_by_query(
    db: &PgPool,
    query: &TemplateQuery,
    page: &PageRequest,
) -> Result<Vec<TaskTemplate>> {
    TaskTemplate::select()
        .where_bind_option("name like '%?'", &query.name)
        .where_bind_option("topic=?", &query.topic)
        .where_bind_option("edition=?", &query.edition)
        .offset(page.offset())
        .limit(page.limit())
        .fetch_all(db)
        .await
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TemplateQuery {
    name: Option<String>,
    topic: Option<TemplateTopic>,
    edition: Option<ProductEdition>,
}

Looking forward to your reply

kurtbuilds commented 10 months ago

Thank you for submitting this.

You can create your own custom trait to add this method to SelectQueryBuilder (or any another) struct. There are ample articles or sections of the Rust Book describing how to do this.

For now, I'll close this issue, as I believe adding such a method to ormlite is beyond its scope because the need doesn't impact enough users.