Skip to content
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

Add #[derive(ormlite::Enum)] Procedural Macro #59

Open
wants to merge 6 commits 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
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ members = [
"macro",
"core",
"ormlite",
"cli"
]
"cli",
]
1 change: 1 addition & 0 deletions macro/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ sqlx = "0.8.2"
lazy_static = "1"
once_cell = "1"
itertools = "0.13.0"
heck = "0.5"
2 changes: 1 addition & 1 deletion macro/src/codegen/insert_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub fn struct_InsertModel(ast: &DeriveInput, attr: &ModelMeta) -> TokenStream {
#vis struct #insert_model {
#(#struct_fields,)*
}
}
}
} else {
quote! {
#[derive(Debug)]
Expand Down
78 changes: 78 additions & 0 deletions macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
#![allow(non_snake_case)]

use codegen::insert::impl_Insert;
use heck::ToSnakeCase;
use ormlite_attr::InsertMeta;
use proc_macro::TokenStream;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::env;
use std::env::var;
use std::ops::Deref;
use syn::DataEnum;

use once_cell::sync::OnceCell;
use quote::quote;
Expand Down Expand Up @@ -250,3 +252,79 @@ pub fn expand_derive_into_arguments(input: TokenStream) -> TokenStream {
pub fn expand_derive_manual_type(input: TokenStream) -> TokenStream {
TokenStream::new()
}

#[proc_macro_derive(Enum)]
pub fn derive_ormlite_enum(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);

let enum_name = input.ident;

let variants = match input.data {
Data::Enum(DataEnum { variants, .. }) => variants,
_ => panic!("#[derive(OrmliteEnum)] is only supported on enums"),
};

// Collect variant names and strings into vectors
let variant_names: Vec<_> = variants.iter().map(|v| &v.ident).collect();
let variant_strings: Vec<_> = variant_names.iter().map(|v| v.to_string().to_snake_case()).collect();

let gen = quote! {
impl std::fmt::Display for #enum_name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
#(Self::#variant_names => write!(f, "{}", #variant_strings)),*
}
}
}

impl std::str::FromStr for #enum_name {
type Err = String;
fn from_str(s: &str) -> Result<Self, <Self as std::str::FromStr>::Err> {
match s {
#(#variant_strings => Ok(Self::#variant_names)),*,
_ => Err(format!("Invalid {} value: {}", stringify!(#enum_name), s))
}
}
}

impl std::convert::TryFrom<&str> for #enum_name {
type Error = String;
fn try_from(value: &str) -> Result<Self, Self::Error> {
<Self as std::str::FromStr>::from_str(value)
}
}

impl sqlx::Decode<'_, sqlx::Postgres> for #enum_name {
fn decode(
value: sqlx::postgres::PgValueRef<'_>,
) -> Result<Self, sqlx::error::BoxDynError> {
let s = value.as_str()?;
<Self as std::str::FromStr>::from_str(s).map_err(|e| sqlx::error::BoxDynError::from(
std::io::Error::new(std::io::ErrorKind::InvalidData, e)
))
}
}

impl sqlx::Encode<'_, sqlx::Postgres> for #enum_name {
fn encode_by_ref(
&self,
buf: &mut sqlx::postgres::PgArgumentBuffer
) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
let s = self.to_string();
<String as sqlx::Encode<sqlx::Postgres>>::encode(s, buf)
}
}

impl sqlx::Type<sqlx::Postgres> for #enum_name {
fn type_info() -> <sqlx::Postgres as sqlx::Database>::TypeInfo {
sqlx::postgres::PgTypeInfo::with_name("VARCHAR")
}

fn compatible(ty: &<sqlx::Postgres as sqlx::Database>::TypeInfo) -> bool {
ty.to_string() == "VARCHAR"
}
}
};

gen.into()
}
7 changes: 4 additions & 3 deletions ormlite/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
#![cfg_attr(docsrs, feature(doc_cfg))]
pub use ::sqlx::{Column, ColumnIndex, Database, Decode, Row};
pub use model::{FromRow, Insert, IntoArguments, Model, TableMeta};
pub use ormlite_core::BoxFuture;
pub use ormlite_core::{Error, Result};
pub use ormlite_macro::Enum;
pub use sqlx::{Column, ColumnIndex, Database, Decode, Row};

pub use ::sqlx::pool::PoolOptions;
pub use ::sqlx::{
pub use sqlx::pool::PoolOptions;
pub use sqlx::{
query, query_as, query_as_with, query_with, Acquire, Arguments, ConnectOptions, Connection, Encode, Executor, Pool,
};

Expand Down