postgres_json_derive/
lib.rs

1use proc_macro::{TokenStream};
2use quote::quote;
3use syn::DeriveInput;
4
5#[proc_macro_derive(ToSqlJson)]
6pub fn postgres_to_sql(input: TokenStream) -> TokenStream {
7    let ast: DeriveInput = syn::parse_macro_input!(input);
8    let name = &ast.ident;
9    let tokens = quote! {
10
11        impl ToSql for #name {
12            fn to_sql(
13                &self,
14                ty: &postgres_types::Type,
15                out: &mut postgres_types::private::BytesMut,
16            ) -> Result<postgres_types::IsNull, Box<dyn std::error::Error + Sync + Send>> {
17                postgres_types::Json(self).to_sql(ty, out)
18            }
19
20            postgres_types::accepts!(JSON, JSONB);
21
22            postgres_types::to_sql_checked!();
23        }
24    };
25    tokens.into()
26}
27
28#[proc_macro_derive(FromSqlJson)]
29pub fn postgres_from_sql(input: TokenStream) -> TokenStream {
30    let ast: DeriveInput = syn::parse_macro_input!(input);
31    let name = &ast.ident;
32    let tokens = quote! {
33        impl<'a> FromSql<'a> for #name {
34            fn from_sql(
35                ty: &postgres_types::Type,
36                raw: &[u8],
37            ) -> Result<#name, Box<dyn std::error::Error + Sync + Send>> {
38                postgres_types::Json::<#name>::from_sql(ty, raw).map(|json| json.0)
39            }
40
41            postgres_types::accepts!(JSON, JSONB);
42        }
43    };
44    tokens.into()
45}