Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add impl FromRow for the unit type #2827

Merged
merged 1 commit into from
Oct 23, 2023
Merged

Conversation

nanoqsh
Copy link
Contributor

@nanoqsh nanoqsh commented Oct 23, 2023

I expected that I could trivially make () from a row, but didn't find this implementation

@abonander
Copy link
Collaborator

I don't really have anything against this but I also don't understand why exactly you would need it, which is why it didn't already exist. Can you provide a motivating example?

@nanoqsh
Copy link
Contributor Author

nanoqsh commented Oct 23, 2023

@abonander

Can you provide a motivating example?

Sure!
In my project I have a type like this:

struct Record<T> {
    id: i32,
    created: DateTime<Utc>,
    data: T,
}

impl<T> Record<T> {
    fn map<F, U>(self, f: F) -> Record<U>
    where
        F: FnOnce(T) -> U,
    {
        Record {
            id: self.id,
            created: self.created,
            data: f(self.data),
        }
    }
}

impl<'a, T> FromRow<'a, PgRow> for Record<T>
where
    T: FromRow<'a, PgRow>,
{
    fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
        Ok(Self {
            id: row.try_get("id")?,
            created: row.try_get("created")?,
            data: T::from_row(row)?,
        })
    }
}

This is some tables generalization, I wanted to bring out some repeating details.
In a higher level model I want to write code something like this:

async fn create<'a>(&self, user: User<'a>) -> sqlx::Result<Record<User<'a>>> {
    sqlx::query("INSERT INTO users (name, pass) VALUES ($1, $2) RETURNING id, created")
        .bind(user.name.as_str())
        .bind(user.pass.as_str())
        .fetch_one(&self.pool)
        .await
        .and_then(|row| {
            let record: Record<()> = Record::from_row(&row)?;
            //                                        ^^^^ the trait `FromRow<'_, PgRow>` is not implemented for `()`
            Ok(record.map(|()| user))
        })
}

And in this way return the user already recorded in the database.
Yes, of course I could return a new user value by listing all of its fields in a new value. But I would like to

  • Simplify the query
  • Reuse lifetime and don't create a new object

@abonander abonander merged commit ba87bf7 into launchbadge:main Oct 23, 2023
64 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants