Skip to content
Open
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
7 changes: 7 additions & 0 deletions sqlx-macros-core/src/derives/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ pub struct SqlxContainerAttributes {
pub repr: Option<Ident>,
pub no_pg_array: bool,
pub default: bool,
pub try_from: Option<Type>,
}

pub enum JsonAttribute {
Expand All @@ -82,6 +83,7 @@ pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result<SqlxContai
let mut rename_all = None;
let mut no_pg_array = None;
let mut default = None;
let mut try_from = None;

for attr in input {
if attr.path().is_ident("sqlx") {
Expand All @@ -92,6 +94,10 @@ pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result<SqlxContai
try_set!(no_pg_array, true, attr);
} else if meta.path.is_ident("default") {
try_set!(default, true, attr);
} else if meta.path.is_ident("try_from") {
meta.input.parse::<Token![=]>()?;
let val: LitStr = meta.input.parse()?;
try_set!(try_from, val.parse()?, val);
} else if meta.path.is_ident("rename_all") {
meta.input.parse::<Token![=]>()?;
let lit: LitStr = meta.input.parse()?;
Expand Down Expand Up @@ -140,6 +146,7 @@ pub fn parse_container_attributes(input: &[Attribute]) -> syn::Result<SqlxContai
rename_all,
no_pg_array: no_pg_array.unwrap_or(false),
default: default.unwrap_or(false),
try_from,
})
}

Expand Down
47 changes: 47 additions & 0 deletions sqlx-macros-core/src/derives/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ use syn::{

pub fn expand_derive_decode(input: &DeriveInput) -> syn::Result<TokenStream> {
let attrs = parse_container_attributes(&input.attrs)?;
if let Some(try_from) = &attrs.try_from {
return expand_derive_decode_try_from(input, try_from);
}

match &input.data {
Data::Struct(DataStruct { fields, .. })
if fields.len() == 1 && (matches!(fields, Fields::Unnamed(_)) || attrs.transparent) =>
Expand Down Expand Up @@ -46,6 +50,49 @@ pub fn expand_derive_decode(input: &DeriveInput) -> syn::Result<TokenStream> {
}
}

fn expand_derive_decode_try_from(
input: &DeriveInput,
try_from: &syn::Type,
) -> syn::Result<TokenStream> {
let ident = &input.ident;
let generics = &input.generics;
let (_, ty_generics, _) = generics.split_for_impl();

let mut generics = generics.clone();
generics
.params
.insert(0, parse_quote!(DB: ::sqlx::Database));
generics.params.insert(0, parse_quote!('r));
generics
.make_where_clause()
.predicates
.push(parse_quote!(#try_from: ::sqlx::decode::Decode<'r, DB>));
generics
.make_where_clause()
.predicates
.push(parse_quote!(#ident #ty_generics: ::std::convert::TryFrom<#try_from>));

let (impl_generics, _, where_clause) = generics.split_for_impl();

Ok(quote!(
#[automatically_derived]
impl #impl_generics ::sqlx::decode::Decode<'r, DB> for #ident #ty_generics #where_clause {
fn decode(
value: <DB as ::sqlx::database::Database>::ValueRef<'r>,
) -> ::std::result::Result<
Self,
::std::boxed::Box<
dyn ::std::error::Error + 'static + ::std::marker::Send + ::std::marker::Sync,
>,
> {
let value = <#try_from as ::sqlx::decode::Decode<'r, DB>>::decode(value)?;
<#ident #ty_generics as ::std::convert::TryFrom<#try_from>>::try_from(value)
.map_err(|e| ::sqlx::__spec_error!(e))
}
}
))
}

fn expand_derive_decode_transparent(
input: &DeriveInput,
field: &Field,
Expand Down
64 changes: 64 additions & 0 deletions sqlx-macros-core/src/derives/type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ use syn::{

pub fn expand_derive_type(input: &DeriveInput) -> syn::Result<TokenStream> {
let attrs = parse_container_attributes(&input.attrs)?;
if let Some(try_from) = &attrs.try_from {
return expand_derive_has_sql_type_try_from(input, try_from, attrs.no_pg_array);
}

match &input.data {
// Newtype structs:
// struct Foo(i32);
Expand Down Expand Up @@ -52,6 +56,66 @@ pub fn expand_derive_type(input: &DeriveInput) -> syn::Result<TokenStream> {
}
}

fn expand_derive_has_sql_type_try_from(
input: &DeriveInput,
try_from: &syn::Type,
no_pg_array: bool,
) -> syn::Result<TokenStream> {
let ident = &input.ident;

let generics = &input.generics;
let (_, ty_generics, _) = generics.split_for_impl();

let mut generics = generics.clone();
let mut array_generics = generics.clone();

generics
.params
.insert(0, parse_quote!(DB: ::sqlx::Database));
generics
.make_where_clause()
.predicates
.push(parse_quote!(#try_from: ::sqlx::Type<DB>));
let (impl_generics, _, where_clause) = generics.split_for_impl();

array_generics
.make_where_clause()
.predicates
.push(parse_quote!(#try_from: ::sqlx::postgres::PgHasArrayType));
let (array_impl_generics, _, array_where_clause) = array_generics.split_for_impl();

let mut tokens = quote!(
#[automatically_derived]
impl #impl_generics ::sqlx::Type<DB> for #ident #ty_generics #where_clause {
fn type_info() -> DB::TypeInfo {
<#try_from as ::sqlx::Type<DB>>::type_info()
}

fn compatible(ty: &DB::TypeInfo) -> ::std::primitive::bool {
<#try_from as ::sqlx::Type<DB>>::compatible(ty)
}
}
);

if cfg!(feature = "postgres") && !no_pg_array {
tokens.extend(quote!(
#[automatically_derived]
impl #array_impl_generics ::sqlx::postgres::PgHasArrayType for #ident #ty_generics
#array_where_clause {
fn array_type_info() -> ::sqlx::postgres::PgTypeInfo {
<#try_from as ::sqlx::postgres::PgHasArrayType>::array_type_info()
}

fn array_compatible(ty: &::sqlx::postgres::PgTypeInfo) -> ::std::primitive::bool {
<#try_from as ::sqlx::postgres::PgHasArrayType>::array_compatible(ty)
}
}
));
}

Ok(tokens)
}

fn expand_derive_has_sql_type_transparent(
input: &DeriveInput,
field: &Field,
Expand Down
17 changes: 17 additions & 0 deletions tests/sqlite/derives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,20 @@ test_type!(transparent_named<TransparentNamed>(Sqlite,
"0" == TransparentNamed { field: 0 },
"23523" == TransparentNamed { field: 23523 },
));

#[derive(PartialEq, Eq, Debug, sqlx::Type)]
#[sqlx(try_from = "i64")]
struct TryFromI64(i64);

impl TryFrom<i64> for TryFromI64 {
type Error = std::num::TryFromIntError;

fn try_from(value: i64) -> Result<Self, Self::Error> {
Ok(Self(i32::try_from(value)? as i64))
}
}

test_type!(try_from_i64<TryFromI64>(Sqlite,
"0" == TryFromI64(0),
"23523" == TryFromI64(23523),
));
Loading