Skip to content

Add support for deriving FromSql and ToSql implementations for structs with references #574

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
5 changes: 5 additions & 0 deletions postgres-derive-test/src/compile-fail/invalid-types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,9 @@ enum FromSqlEnum {
Foo(i32),
}

#[derive(FromSql)]
struct FromSqlTypeParameter<T> {
foo: T,
}

fn main() {}
6 changes: 6 additions & 0 deletions postgres-derive-test/src/compile-fail/invalid-types.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,9 @@ error: non-C-like enums are not supported
|
22 | Foo(i32),
| ^^^^^^^^

error: #[derive(FromSql)] does not support type parameters.
--> $DIR/invalid-types.rs:26:28
|
26 | struct FromSqlTypeParameter<T> {
| ^^^
29 changes: 29 additions & 0 deletions postgres-derive-test/src/composites.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,32 @@ fn wrong_type() {
.unwrap_err();
assert!(err.source().unwrap().is::<WrongType>());
}

#[test]
fn struct_with_references() {
#[derive(FromSql, ToSql, Debug, PartialEq)]
#[postgres(name = "item")]
struct Item<'a, 'b: 'a> {
name: &'a str,
data: &'b [u8],
}

let mut conn = Client::connect("user=postgres host=localhost port=5433", NoTls).unwrap();
conn.batch_execute(
"CREATE TYPE pg_temp.item AS (
name TEXT,
data BYTEA
);",
)
.unwrap();

let item = Item {
name: "foobar",
data: b"12345",
};

let row = conn.query_one("SELECT $1::item", &[&item]).unwrap();
let result: Item<'_, '_> = row.get(0);
assert_eq!(item.name, result.name);
assert_eq!(item.data, result.data);
}
20 changes: 20 additions & 0 deletions postgres-derive-test/src/domains.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,23 @@ fn domain_in_composite() {
)],
);
}

#[test]
fn struct_with_reference() {
#[derive(FromSql, ToSql, Debug, PartialEq)]
struct SessionId<'b>(&'b [u8]);

let mut conn = Client::connect("user=postgres host=localhost port=5433", NoTls).unwrap();
conn.execute(
"CREATE DOMAIN pg_temp.\"SessionId\" AS bytea CHECK(octet_length(VALUE) = 16);",
&[],
)
.unwrap();

let session_id = b"0123456789abcdef";
let row = conn
.query_one("SELECT $1::\"SessionId\"", &[&SessionId(session_id)])
.unwrap();
let result: SessionId<'_> = row.get(0);
assert_eq!(session_id, result.0);
}
31 changes: 28 additions & 3 deletions postgres-derive/src/fromsql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use crate::composites::Field;
use crate::enums::Variant;
use crate::overrides::Overrides;

const DEFAULT_LIFETIME: &str = "de";

pub fn expand_derive_fromsql(input: DeriveInput) -> Result<TokenStream, Error> {
let overrides = Overrides::extract(&input.attrs)?;

Expand Down Expand Up @@ -58,10 +60,33 @@ pub fn expand_derive_fromsql(input: DeriveInput) -> Result<TokenStream, Error> {
};

let ident = &input.ident;
let mut generics = input.generics;
if generics.type_params().count() > 0 {
return Err(Error::new_spanned(
&generics,
"#[derive(FromSql)] does not support type parameters.",
));
}

let generics_clone = &generics.clone();
let (_, type_generics, _) = generics_clone.split_for_impl();

let lifetime = syn::Lifetime::new(&format!("'{}", DEFAULT_LIFETIME), Span::call_site());
let mut lifetime_def = syn::LifetimeDef::new(lifetime.clone());
let lifetimes: Vec<syn::Lifetime> = generics.lifetimes().map(|l| l.lifetime.clone()).collect();
lifetime_def.bounds = syn::punctuated::Punctuated::new();
for l in lifetimes {
lifetime_def.bounds.push(l);
}
generics
.params
.push(syn::GenericParam::Lifetime(lifetime_def));
let (impl_generics, _, _) = generics.split_for_impl();

let out = quote! {
impl<'a> postgres_types::FromSql<'a> for #ident {
fn from_sql(_type: &postgres_types::Type, buf: &'a [u8])
-> std::result::Result<#ident,
impl #impl_generics postgres_types::FromSql<#lifetime> for #ident #type_generics {
fn from_sql(_type: &postgres_types::Type, buf: & #lifetime [u8])
-> std::result::Result<#ident #type_generics,
std::boxed::Box<dyn std::error::Error +
std::marker::Sync +
std::marker::Send>> {
Expand Down
4 changes: 3 additions & 1 deletion postgres-derive/src/tosql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,10 @@ pub fn expand_derive_tosql(input: DeriveInput) -> Result<TokenStream, Error> {
};

let ident = &input.ident;
let generics = &input.generics;
let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
let out = quote! {
impl postgres_types::ToSql for #ident {
impl #impl_generics postgres_types::ToSql for #ident #type_generics #where_clause {
fn to_sql(&self,
_type: &postgres_types::Type,
buf: &mut postgres_types::private::BytesMut)
Expand Down