ormlite icon indicating copy to clipboard operation
ormlite copied to clipboard

Support for newtype in models?

Open SpartanPlume opened this issue 6 months ago • 4 comments

Hello,

I just discovered this library and it seems to correspond to what I want for use in my project, however I am currently using the newtype pattern which I wonder if it can be used with this library.

My usecase: I use axum to create an API and I would like to be able to validate the input given by the user via the newtype pattern and then use it for the insertion in the database. For now I only considered the insertion and not the update of a table.

My current model with sqlx (not migrated to ormlite yet):

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Tournament {
    pub id: i32,
    pub name: String,
    pub acronym: String,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Deserialize, Clone)]
pub struct NewTournament {
    pub name: TournamentName,
    pub acronym: TournamentAcronym,
}

TournamentName and TournamentAcronym wraps a String type with the newtype pattern.

With sqlx, I have this function for the insertion:

pub async fn insert(&self, db_pool: &DbPool) -> Result<Tournament, anyhow::Error> {
    let tournament = sqlx::query_as!(
        Tournament,
        "INSERT INTO tournaments (name, acronym) VALUES ($1, $2) RETURNING *",
        self.name.as_ref(),
        self.acronym.as_ref()
    )
    .fetch_one(db_pool)
    .await
    .context("Could not retrieve tournament by id from database")?;
    Ok(tournament)
}

So it was using .as_ref() to get the underlying &str.

When I try to convert the model to use ormlite, I get this error: the trait bound TournamentAcronym: Type<Postgres> is not satisfied

Is there a way to have the newtype pattern working by maybe doing some code modification on the newtype or the model? And if not, do you think it could be possible to add support for the newtype pattern in models?

SpartanPlume avatar Aug 27 '24 20:08 SpartanPlume