Achieve Optional Trait Implementation for trait methods

I have a trait Definition thus:


#[async_trait]
pub trait SqlQueryBuilder {
    /// allow generic use of the query builder for multiple models
    type Entity;
    type Attributes;
    type UpdatedAttribute;

    /// save a new record in the database
    async fn save(
        fields: Self::Attributes,
        db_connection: &Pool<Postgres>,
    ) -> Result<Self::Entity, sqlx::Error>;

    /// update a field e.g user password
    async fn update_field(
        field: &str,
        value: Self::UpdatedAttribute,
        db_connection: &Pool<Postgres>,
    ) -> Result<Self::Entity, sqlx::Error>;

    /// find record by id
    async fn find_by_id(
        id: &str,
        db_connection: &Pool<Postgres>,
    ) -> Result<Self::Entity, sqlx::Error>;
}

I want to be able to Implement not necessarily all methods defined in the trait for a struct as seen in the case below:

impl SqlQueryBuilder for UserModel {
    type Entity = UserModel;
    type Attributes = UserInformation;
    /// save a new record in the database
    async fn save(
        fields: Self::Attributes,
        db_connection: &Pool<Postgres>,
    ) -> Result<Self::Entity, sqlx::Error> {
       ...
    }

    /// find user by id
    async fn find_by_id(
        id: &str,
        db_connection: &Pool<Postgres>,
    ) -> Result<Self::Entity, sqlx::Error> {
        sqlx::query_as::<_, UserModel>("SELECT * FROM user_information WHERE id = $1")
            .bind(sqlx::types::Uuid::parse_str(id).unwrap())
            .fetch_one(db_connection)
            .await
    }
}

How can I achieve this?

You can write a default implemention. You can also split that trait into smaller traits.

2 Likes

Any guide on default implementation, I'd like to keep the traits together for code organization

Just write a body to your function:

trait Foo {
    fn foo(&self) -> i32 { 0 }
}
2 Likes

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.