postgres-derive-0.4.5/.cargo_vcs_info.json0000644000000001550000000000100141650ustar { "git": { "sha1": "43e15690f492f3ae8088677fd8d5df18f73b3e85" }, "path_in_vcs": "postgres-derive" }postgres-derive-0.4.5/CHANGELOG.md000064400000000000000000000011361046102023000145660ustar 00000000000000# Change Log ## v0.4.5 - 2023-08-19 ### Added * Added a `rename_all` option for enum and struct derives. * Added an `allow_mismatch` option to disable strict enum variant checks against the Postgres type. ## v0.4.4 - 2023-03-27 ### Changed * Upgraded `syn`. ## v0.4.3 - 2022-09-07 ### Added * Added support for parameterized structs. ## v0.4.2 - 2022-04-30 ### Added * Added support for transparent wrapper types. ## v0.4.1 - 2021-11-23 ### Fixed * Fixed handling of struct fields using raw identifiers. ## v0.4.0 - 2019-12-23 No changes ## v0.4.0-alpha.1 - 2019-10-14 * Initial release postgres-derive-0.4.5/Cargo.toml0000644000000016530000000000100121670ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "postgres-derive" version = "0.4.5" authors = ["Steven Fackler "] description = "An internal crate used by postgres-types" license = "MIT/Apache-2.0" repository = "https://github.com/sfackler/rust-postgres" resolver = "2" [lib] test = false proc-macro = true [dependencies.heck] version = "0.4" [dependencies.proc-macro2] version = "1.0" [dependencies.quote] version = "1.0" [dependencies.syn] version = "2.0" postgres-derive-0.4.5/Cargo.toml.orig000064400000000000000000000005701046102023000156450ustar 00000000000000[package] name = "postgres-derive" version = "0.4.5" authors = ["Steven Fackler "] license = "MIT/Apache-2.0" edition = "2018" description = "An internal crate used by postgres-types" repository = "https://github.com/sfackler/rust-postgres" [lib] proc-macro = true test = false [dependencies] syn = "2.0" proc-macro2 = "1.0" quote = "1.0" heck = "0.4"postgres-derive-0.4.5/LICENSE-APACHE000064400000000000000000000251371046102023000147100ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. postgres-derive-0.4.5/LICENSE-MIT000064400000000000000000000020721046102023000144110ustar 00000000000000The MIT License (MIT) Copyright (c) 2016 Steven Fackler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. postgres-derive-0.4.5/src/accepts.rs000064400000000000000000000052301046102023000155330ustar 00000000000000use proc_macro2::{Span, TokenStream}; use quote::quote; use std::iter; use syn::Ident; use crate::composites::Field; use crate::enums::Variant; pub fn transparent_body(field: &syn::Field) -> TokenStream { let ty = &field.ty; quote! { <#ty as ::postgres_types::ToSql>::accepts(type_) } } pub fn domain_body(name: &str, field: &syn::Field) -> TokenStream { let ty = &field.ty; quote! { if type_.name() != #name { return false; } match *type_.kind() { ::postgres_types::Kind::Domain(ref type_) => { <#ty as ::postgres_types::ToSql>::accepts(type_) } _ => false, } } } pub fn enum_body(name: &str, variants: &[Variant], allow_mismatch: bool) -> TokenStream { let num_variants = variants.len(); let variant_names = variants.iter().map(|v| &v.name); if allow_mismatch { quote! { type_.name() == #name } } else { quote! { if type_.name() != #name { return false; } match *type_.kind() { ::postgres_types::Kind::Enum(ref variants) => { if variants.len() != #num_variants { return false; } variants.iter().all(|v| { match &**v { #( #variant_names => true, )* _ => false, } }) } _ => false, } } } } pub fn composite_body(name: &str, trait_: &str, fields: &[Field]) -> TokenStream { let num_fields = fields.len(); let trait_ = Ident::new(trait_, Span::call_site()); let traits = iter::repeat(&trait_); let field_names = fields.iter().map(|f| &f.name); let field_types = fields.iter().map(|f| &f.type_); quote! { if type_.name() != #name { return false; } match *type_.kind() { ::postgres_types::Kind::Composite(ref fields) => { if fields.len() != #num_fields { return false; } fields.iter().all(|f| { match f.name() { #( #field_names => { <#field_types as ::postgres_types::#traits>::accepts(f.type_()) } )* _ => false, } }) } _ => false, } } } postgres-derive-0.4.5/src/case.rs000064400000000000000000000073611046102023000150330ustar 00000000000000#[allow(deprecated, unused_imports)] use std::ascii::AsciiExt; use heck::{ ToKebabCase, ToLowerCamelCase, ToShoutyKebabCase, ToShoutySnakeCase, ToSnakeCase, ToTrainCase, ToUpperCamelCase, }; use self::RenameRule::*; /// The different possible ways to change case of fields in a struct, or variants in an enum. #[allow(clippy::enum_variant_names)] #[derive(Copy, Clone, PartialEq)] pub enum RenameRule { /// Rename direct children to "lowercase" style. LowerCase, /// Rename direct children to "UPPERCASE" style. UpperCase, /// Rename direct children to "PascalCase" style, as typically used for /// enum variants. PascalCase, /// Rename direct children to "camelCase" style. CamelCase, /// Rename direct children to "snake_case" style, as commonly used for /// fields. SnakeCase, /// Rename direct children to "SCREAMING_SNAKE_CASE" style, as commonly /// used for constants. ScreamingSnakeCase, /// Rename direct children to "kebab-case" style. KebabCase, /// Rename direct children to "SCREAMING-KEBAB-CASE" style. ScreamingKebabCase, /// Rename direct children to "Train-Case" style. TrainCase, } pub const RENAME_RULES: &[&str] = &[ "lowercase", "UPPERCASE", "PascalCase", "camelCase", "snake_case", "SCREAMING_SNAKE_CASE", "kebab-case", "SCREAMING-KEBAB-CASE", "Train-Case", ]; impl RenameRule { pub fn from_str(rule: &str) -> Option { match rule { "lowercase" => Some(LowerCase), "UPPERCASE" => Some(UpperCase), "PascalCase" => Some(PascalCase), "camelCase" => Some(CamelCase), "snake_case" => Some(SnakeCase), "SCREAMING_SNAKE_CASE" => Some(ScreamingSnakeCase), "kebab-case" => Some(KebabCase), "SCREAMING-KEBAB-CASE" => Some(ScreamingKebabCase), "Train-Case" => Some(TrainCase), _ => None, } } /// Apply a renaming rule to an enum or struct field, returning the version expected in the source. pub fn apply_to_field(&self, variant: &str) -> String { match *self { LowerCase => variant.to_lowercase(), UpperCase => variant.to_uppercase(), PascalCase => variant.to_upper_camel_case(), CamelCase => variant.to_lower_camel_case(), SnakeCase => variant.to_snake_case(), ScreamingSnakeCase => variant.to_shouty_snake_case(), KebabCase => variant.to_kebab_case(), ScreamingKebabCase => variant.to_shouty_kebab_case(), TrainCase => variant.to_train_case(), } } } #[test] fn rename_field() { for &(original, lower, upper, camel, snake, screaming, kebab, screaming_kebab) in &[ ( "Outcome", "outcome", "OUTCOME", "outcome", "outcome", "OUTCOME", "outcome", "OUTCOME", ), ( "VeryTasty", "verytasty", "VERYTASTY", "veryTasty", "very_tasty", "VERY_TASTY", "very-tasty", "VERY-TASTY", ), ("A", "a", "A", "a", "a", "A", "a", "A"), ("Z42", "z42", "Z42", "z42", "z42", "Z42", "z42", "Z42"), ] { assert_eq!(LowerCase.apply_to_field(original), lower); assert_eq!(UpperCase.apply_to_field(original), upper); assert_eq!(PascalCase.apply_to_field(original), original); assert_eq!(CamelCase.apply_to_field(original), camel); assert_eq!(SnakeCase.apply_to_field(original), snake); assert_eq!(ScreamingSnakeCase.apply_to_field(original), screaming); assert_eq!(KebabCase.apply_to_field(original), kebab); assert_eq!(ScreamingKebabCase.apply_to_field(original), screaming_kebab); } } postgres-derive-0.4.5/src/composites.rs000064400000000000000000000032331046102023000162770ustar 00000000000000use proc_macro2::Span; use syn::{ punctuated::Punctuated, Error, GenericParam, Generics, Ident, Path, PathSegment, Type, TypeParamBound, }; use crate::{case::RenameRule, overrides::Overrides}; pub struct Field { pub name: String, pub ident: Ident, pub type_: Type, } impl Field { pub fn parse(raw: &syn::Field, rename_all: Option) -> Result { let overrides = Overrides::extract(&raw.attrs, false)?; let ident = raw.ident.as_ref().unwrap().clone(); // field level name override takes precendence over container level rename_all override let name = match overrides.name { Some(n) => n, None => { let name = ident.to_string(); let stripped = name.strip_prefix("r#").map(String::from).unwrap_or(name); match rename_all { Some(rule) => rule.apply_to_field(&stripped), None => stripped, } } }; Ok(Field { name, ident, type_: raw.ty.clone(), }) } } pub(crate) fn append_generic_bound(mut generics: Generics, bound: &TypeParamBound) -> Generics { for param in &mut generics.params { if let GenericParam::Type(param) = param { param.bounds.push(bound.to_owned()) } } generics } pub(crate) fn new_derive_path(last: PathSegment) -> Path { let mut path = Path { leading_colon: None, segments: Punctuated::new(), }; path.segments .push(Ident::new("postgres_types", Span::call_site()).into()); path.segments.push(last); path } postgres-derive-0.4.5/src/enums.rs000064400000000000000000000017161046102023000152450ustar 00000000000000use syn::{Error, Fields, Ident}; use crate::{case::RenameRule, overrides::Overrides}; pub struct Variant { pub ident: Ident, pub name: String, } impl Variant { pub fn parse(raw: &syn::Variant, rename_all: Option) -> Result { match raw.fields { Fields::Unit => {} _ => { return Err(Error::new_spanned( raw, "non-C-like enums are not supported", )) } } let overrides = Overrides::extract(&raw.attrs, false)?; // variant level name override takes precendence over container level rename_all override let name = overrides.name.unwrap_or_else(|| match rename_all { Some(rule) => rule.apply_to_field(&raw.ident.to_string()), None => raw.ident.to_string(), }); Ok(Variant { ident: raw.ident.clone(), name, }) } } postgres-derive-0.4.5/src/fromsql.rs000064400000000000000000000216551046102023000156050ustar 00000000000000use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use std::iter; use syn::{ punctuated::Punctuated, token, AngleBracketedGenericArguments, Data, DataStruct, DeriveInput, Error, Fields, GenericArgument, GenericParam, Generics, Ident, Lifetime, PathArguments, PathSegment, }; use syn::{LifetimeParam, TraitBound, TraitBoundModifier, TypeParamBound}; use crate::accepts; use crate::composites::Field; use crate::composites::{append_generic_bound, new_derive_path}; use crate::enums::Variant; use crate::overrides::Overrides; pub fn expand_derive_fromsql(input: DeriveInput) -> Result { let overrides = Overrides::extract(&input.attrs, true)?; if (overrides.name.is_some() || overrides.rename_all.is_some()) && overrides.transparent { return Err(Error::new_spanned( &input, "#[postgres(transparent)] is not allowed with #[postgres(name = \"...\")] or #[postgres(rename_all = \"...\")]", )); } let name = overrides .name .clone() .unwrap_or_else(|| input.ident.to_string()); let (accepts_body, to_sql_body) = if overrides.transparent { match input.data { Data::Struct(DataStruct { fields: Fields::Unnamed(ref fields), .. }) if fields.unnamed.len() == 1 => { let field = fields.unnamed.first().unwrap(); ( accepts::transparent_body(field), transparent_body(&input.ident, field), ) } _ => { return Err(Error::new_spanned( input, "#[postgres(transparent)] may only be applied to single field tuple structs", )) } } } else if overrides.allow_mismatch { match input.data { Data::Enum(ref data) => { let variants = data .variants .iter() .map(|variant| Variant::parse(variant, overrides.rename_all)) .collect::, _>>()?; ( accepts::enum_body(&name, &variants, overrides.allow_mismatch), enum_body(&input.ident, &variants), ) } _ => { return Err(Error::new_spanned( input, "#[postgres(allow_mismatch)] may only be applied to enums", )); } } } else { match input.data { Data::Enum(ref data) => { let variants = data .variants .iter() .map(|variant| Variant::parse(variant, overrides.rename_all)) .collect::, _>>()?; ( accepts::enum_body(&name, &variants, overrides.allow_mismatch), enum_body(&input.ident, &variants), ) } Data::Struct(DataStruct { fields: Fields::Unnamed(ref fields), .. }) if fields.unnamed.len() == 1 => { let field = fields.unnamed.first().unwrap(); ( domain_accepts_body(&name, field), domain_body(&input.ident, field), ) } Data::Struct(DataStruct { fields: Fields::Named(ref fields), .. }) => { let fields = fields .named .iter() .map(|field| Field::parse(field, overrides.rename_all)) .collect::, _>>()?; ( accepts::composite_body(&name, "FromSql", &fields), composite_body(&input.ident, &fields), ) } _ => { return Err(Error::new_spanned( input, "#[derive(FromSql)] may only be applied to structs, single field tuple structs, and enums", )) } } }; let ident = &input.ident; let (generics, lifetime) = build_generics(&input.generics); let (impl_generics, _, _) = generics.split_for_impl(); let (_, ty_generics, where_clause) = input.generics.split_for_impl(); let out = quote! { impl #impl_generics postgres_types::FromSql<#lifetime> for #ident #ty_generics #where_clause { fn from_sql(_type: &postgres_types::Type, buf: &#lifetime [u8]) -> std::result::Result<#ident #ty_generics, std::boxed::Box> { #to_sql_body } fn accepts(type_: &postgres_types::Type) -> bool { #accepts_body } } }; Ok(out) } fn transparent_body(ident: &Ident, field: &syn::Field) -> TokenStream { let ty = &field.ty; quote! { <#ty as postgres_types::FromSql>::from_sql(_type, buf).map(#ident) } } fn enum_body(ident: &Ident, variants: &[Variant]) -> TokenStream { let variant_names = variants.iter().map(|v| &v.name); let idents = iter::repeat(ident); let variant_idents = variants.iter().map(|v| &v.ident); quote! { match std::str::from_utf8(buf)? { #( #variant_names => std::result::Result::Ok(#idents::#variant_idents), )* s => { std::result::Result::Err( std::convert::Into::into(format!("invalid variant `{}`", s))) } } } } // Domains are sometimes but not always just represented by the bare type (!?) fn domain_accepts_body(name: &str, field: &syn::Field) -> TokenStream { let ty = &field.ty; let normal_body = accepts::domain_body(name, field); quote! { if <#ty as postgres_types::FromSql>::accepts(type_) { return true; } #normal_body } } fn domain_body(ident: &Ident, field: &syn::Field) -> TokenStream { let ty = &field.ty; quote! { <#ty as postgres_types::FromSql>::from_sql(_type, buf).map(#ident) } } fn composite_body(ident: &Ident, fields: &[Field]) -> TokenStream { let temp_vars = &fields .iter() .map(|f| format_ident!("__{}", f.ident)) .collect::>(); let field_names = &fields.iter().map(|f| &f.name).collect::>(); let field_idents = &fields.iter().map(|f| &f.ident).collect::>(); quote! { let fields = match *_type.kind() { postgres_types::Kind::Composite(ref fields) => fields, _ => unreachable!(), }; let mut buf = buf; let num_fields = postgres_types::private::read_be_i32(&mut buf)?; if num_fields as usize != fields.len() { return std::result::Result::Err( std::convert::Into::into(format!("invalid field count: {} vs {}", num_fields, fields.len()))); } #( let mut #temp_vars = std::option::Option::None; )* for field in fields { let oid = postgres_types::private::read_be_i32(&mut buf)? as u32; if oid != field.type_().oid() { return std::result::Result::Err(std::convert::Into::into("unexpected OID")); } match field.name() { #( #field_names => { #temp_vars = std::option::Option::Some( postgres_types::private::read_value(field.type_(), &mut buf)?); } )* _ => unreachable!(), } } std::result::Result::Ok(#ident { #( #field_idents: #temp_vars.unwrap(), )* }) } } fn build_generics(source: &Generics) -> (Generics, Lifetime) { // don't worry about lifetime name collisions, it doesn't make sense to derive FromSql on a struct with a lifetime let lifetime = Lifetime::new("'a", Span::call_site()); let mut out = append_generic_bound(source.to_owned(), &new_fromsql_bound(&lifetime)); out.params.insert( 0, GenericParam::Lifetime(LifetimeParam::new(lifetime.to_owned())), ); (out, lifetime) } fn new_fromsql_bound(lifetime: &Lifetime) -> TypeParamBound { let mut path_segment: PathSegment = Ident::new("FromSql", Span::call_site()).into(); let mut seg_args = Punctuated::new(); seg_args.push(GenericArgument::Lifetime(lifetime.to_owned())); path_segment.arguments = PathArguments::AngleBracketed(AngleBracketedGenericArguments { colon2_token: None, lt_token: token::Lt::default(), args: seg_args, gt_token: token::Gt::default(), }); TypeParamBound::Trait(TraitBound { lifetimes: None, modifier: TraitBoundModifier::None, paren_token: None, path: new_derive_path(path_segment), }) } postgres-derive-0.4.5/src/lib.rs000064400000000000000000000014021046102023000146540ustar 00000000000000//! An internal crate for `postgres-types`. #![recursion_limit = "256"] extern crate proc_macro; use proc_macro::TokenStream; use syn::parse_macro_input; mod accepts; mod case; mod composites; mod enums; mod fromsql; mod overrides; mod tosql; #[proc_macro_derive(ToSql, attributes(postgres))] pub fn derive_tosql(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input); tosql::expand_derive_tosql(input) .unwrap_or_else(|e| e.to_compile_error()) .into() } #[proc_macro_derive(FromSql, attributes(postgres))] pub fn derive_fromsql(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input); fromsql::expand_derive_fromsql(input) .unwrap_or_else(|e| e.to_compile_error()) .into() } postgres-derive-0.4.5/src/overrides.rs000064400000000000000000000105351046102023000161170ustar 00000000000000use syn::punctuated::Punctuated; use syn::{Attribute, Error, Expr, ExprLit, Lit, Meta, Token}; use crate::case::{RenameRule, RENAME_RULES}; pub struct Overrides { pub name: Option, pub rename_all: Option, pub transparent: bool, pub allow_mismatch: bool, } impl Overrides { pub fn extract(attrs: &[Attribute], container_attr: bool) -> Result { let mut overrides = Overrides { name: None, rename_all: None, transparent: false, allow_mismatch: false, }; for attr in attrs { if !attr.path().is_ident("postgres") { continue; } let list = match &attr.meta { Meta::List(ref list) => list, bad => return Err(Error::new_spanned(bad, "expected a #[postgres(...)]")), }; let nested = list.parse_args_with(Punctuated::::parse_terminated)?; for item in nested { match item { Meta::NameValue(meta) => { let name_override = meta.path.is_ident("name"); let rename_all_override = meta.path.is_ident("rename_all"); if !container_attr && rename_all_override { return Err(Error::new_spanned( &meta.path, "rename_all is a container attribute", )); } if !name_override && !rename_all_override { return Err(Error::new_spanned(&meta.path, "unknown override")); } let value = match &meta.value { Expr::Lit(ExprLit { lit: Lit::Str(lit), .. }) => lit.value(), bad => { return Err(Error::new_spanned(bad, "expected a string literal")) } }; if name_override { overrides.name = Some(value); } else if rename_all_override { let rename_rule = RenameRule::from_str(&value).ok_or_else(|| { Error::new_spanned( &meta.value, format!( "invalid rename_all rule, expected one of: {}", RENAME_RULES .iter() .map(|rule| format!("\"{}\"", rule)) .collect::>() .join(", ") ), ) })?; overrides.rename_all = Some(rename_rule); } } Meta::Path(path) => { if path.is_ident("transparent") { if overrides.allow_mismatch { return Err(Error::new_spanned( path, "#[postgres(allow_mismatch)] is not allowed with #[postgres(transparent)]", )); } overrides.transparent = true; } else if path.is_ident("allow_mismatch") { if overrides.transparent { return Err(Error::new_spanned( path, "#[postgres(transparent)] is not allowed with #[postgres(allow_mismatch)]", )); } overrides.allow_mismatch = true; } else { return Err(Error::new_spanned(path, "unknown override")); } } bad => return Err(Error::new_spanned(bad, "unknown attribute")), } } } Ok(overrides) } } postgres-derive-0.4.5/src/tosql.rs000064400000000000000000000164241046102023000152620ustar 00000000000000use proc_macro2::{Span, TokenStream}; use quote::quote; use std::iter; use syn::{ Data, DataStruct, DeriveInput, Error, Fields, Ident, TraitBound, TraitBoundModifier, TypeParamBound, }; use crate::accepts; use crate::composites::Field; use crate::composites::{append_generic_bound, new_derive_path}; use crate::enums::Variant; use crate::overrides::Overrides; pub fn expand_derive_tosql(input: DeriveInput) -> Result { let overrides = Overrides::extract(&input.attrs, true)?; if (overrides.name.is_some() || overrides.rename_all.is_some()) && overrides.transparent { return Err(Error::new_spanned( &input, "#[postgres(transparent)] is not allowed with #[postgres(name = \"...\")] or #[postgres(rename_all = \"...\")]", )); } let name = overrides .name .clone() .unwrap_or_else(|| input.ident.to_string()); let (accepts_body, to_sql_body) = if overrides.transparent { match input.data { Data::Struct(DataStruct { fields: Fields::Unnamed(ref fields), .. }) if fields.unnamed.len() == 1 => { let field = fields.unnamed.first().unwrap(); (accepts::transparent_body(field), transparent_body()) } _ => { return Err(Error::new_spanned( input, "#[postgres(transparent)] may only be applied to single field tuple structs", )); } } } else if overrides.allow_mismatch { match input.data { Data::Enum(ref data) => { let variants = data .variants .iter() .map(|variant| Variant::parse(variant, overrides.rename_all)) .collect::, _>>()?; ( accepts::enum_body(&name, &variants, overrides.allow_mismatch), enum_body(&input.ident, &variants), ) } _ => { return Err(Error::new_spanned( input, "#[postgres(allow_mismatch)] may only be applied to enums", )); } } } else { match input.data { Data::Enum(ref data) => { let variants = data .variants .iter() .map(|variant| Variant::parse(variant, overrides.rename_all)) .collect::, _>>()?; ( accepts::enum_body(&name, &variants, overrides.allow_mismatch), enum_body(&input.ident, &variants), ) } Data::Struct(DataStruct { fields: Fields::Unnamed(ref fields), .. }) if fields.unnamed.len() == 1 => { let field = fields.unnamed.first().unwrap(); (accepts::domain_body(&name, field), domain_body()) } Data::Struct(DataStruct { fields: Fields::Named(ref fields), .. }) => { let fields = fields .named .iter() .map(|field| Field::parse(field, overrides.rename_all)) .collect::, _>>()?; ( accepts::composite_body(&name, "ToSql", &fields), composite_body(&fields), ) } _ => { return Err(Error::new_spanned( input, "#[derive(ToSql)] may only be applied to structs, single field tuple structs, and enums", )); } } }; let ident = &input.ident; let generics = append_generic_bound(input.generics.to_owned(), &new_tosql_bound()); let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let out = quote! { impl#impl_generics postgres_types::ToSql for #ident#ty_generics #where_clause { fn to_sql(&self, _type: &postgres_types::Type, buf: &mut postgres_types::private::BytesMut) -> std::result::Result> { #to_sql_body } fn accepts(type_: &postgres_types::Type) -> bool { #accepts_body } postgres_types::to_sql_checked!(); } }; Ok(out) } fn transparent_body() -> TokenStream { quote! { postgres_types::ToSql::to_sql(&self.0, _type, buf) } } fn enum_body(ident: &Ident, variants: &[Variant]) -> TokenStream { let idents = iter::repeat(ident); let variant_idents = variants.iter().map(|v| &v.ident); let variant_names = variants.iter().map(|v| &v.name); quote! { let s = match *self { #( #idents::#variant_idents => #variant_names, )* }; buf.extend_from_slice(s.as_bytes()); std::result::Result::Ok(postgres_types::IsNull::No) } } fn domain_body() -> TokenStream { quote! { let type_ = match *_type.kind() { postgres_types::Kind::Domain(ref type_) => type_, _ => unreachable!(), }; postgres_types::ToSql::to_sql(&self.0, type_, buf) } } fn composite_body(fields: &[Field]) -> TokenStream { let field_names = fields.iter().map(|f| &f.name); let field_idents = fields.iter().map(|f| &f.ident); quote! { let fields = match *_type.kind() { postgres_types::Kind::Composite(ref fields) => fields, _ => unreachable!(), }; buf.extend_from_slice(&(fields.len() as i32).to_be_bytes()); for field in fields { buf.extend_from_slice(&field.type_().oid().to_be_bytes()); let base = buf.len(); buf.extend_from_slice(&[0; 4]); let r = match field.name() { #( #field_names => postgres_types::ToSql::to_sql(&self.#field_idents, field.type_(), buf), )* _ => unreachable!(), }; let count = match r? { postgres_types::IsNull::Yes => -1, postgres_types::IsNull::No => { let len = buf.len() - base - 4; if len > i32::max_value() as usize { return std::result::Result::Err( std::convert::Into::into("value too large to transmit")); } len as i32 } }; buf[base..base + 4].copy_from_slice(&count.to_be_bytes()); } std::result::Result::Ok(postgres_types::IsNull::No) } } fn new_tosql_bound() -> TypeParamBound { TypeParamBound::Trait(TraitBound { lifetimes: None, modifier: TraitBoundModifier::None, paren_token: None, path: new_derive_path(Ident::new("ToSql", Span::call_site()).into()), }) }