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

Allow using complex types in try_from when deriving FromRow #2115

Merged
merged 2 commits into from
Feb 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions sqlx-macros-core/src/derives/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use quote::{quote, quote_spanned};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::token::Comma;
use syn::{Attribute, DeriveInput, Field, Lit, Meta, MetaNameValue, NestedMeta, Variant};
use syn::{Attribute, DeriveInput, Field, Lit, Meta, MetaNameValue, NestedMeta, Type, Variant};

macro_rules! assert_attribute {
($e:expr, $err:expr, $input:expr) => {
Expand Down Expand Up @@ -62,7 +62,7 @@ pub struct SqlxChildAttributes {
pub rename: Option<String>,
pub default: bool,
pub flatten: bool,
pub try_from: Option<Ident>,
pub try_from: Option<Type>,
}

pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result<SqlxContainerAttributes> {
Expand Down
33 changes: 33 additions & 0 deletions tests/mysql/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -435,4 +435,37 @@ async fn test_try_from_attr_with_flatten() -> anyhow::Result<()> {
Ok(())
}

#[sqlx_macros::test]
async fn test_try_from_attr_with_complex_type() -> anyhow::Result<()> {
mod m {
#[derive(sqlx::Type)]
#[sqlx(transparent)]
pub struct ComplexType<T>(T);

impl std::convert::TryFrom<ComplexType<i64>> for u64 {
type Error = std::num::TryFromIntError;
fn try_from(value: ComplexType<i64>) -> Result<Self, Self::Error> {
u64::try_from(value.0)
}
}
}

#[derive(sqlx::FromRow)]
struct Record {
#[sqlx(try_from = "m::ComplexType<i64>")]
id: u64,
}

let mut conn = new::<MySql>().await?;
let (mut conn, id) = with_test_row(&mut conn).await?;

let record = sqlx::query_as::<_, Record>("select id from tweet")
.fetch_one(&mut *conn)
.await?;

assert_eq!(record.id, id.0 as u64);

Ok(())
}

// we don't emit bind parameter type-checks for MySQL so testing the overrides is redundant