Skip to content

Commit

Permalink
Allow using complex types in try_from when deriving FromRow (laun…
Browse files Browse the repository at this point in the history
…chbadge#2115)

* Use `syn::Type` instead of `syn::Ident` to parse the value of `#[sqlx(try_from = "...")]`

* Fix broken test after rebase
  • Loading branch information
95ulisse authored and grgi committed Feb 14, 2023
1 parent 2718d6f commit 4336a63
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
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 skip: bool,
}

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

0 comments on commit 4336a63

Please sign in to comment.