use std::collections::BTreeMap;
use heck::{ToShoutySnakeCase as _, ToSnakeCase as _};
use quote::{format_ident, quote};
use crate::{
method::{Emitted, Origin, Owner},
model::{DatabaseKind, GraphqlKind},
};
mod own;
mod remote;
#[cfg(test)]
mod tests;
mod wire;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum StorageForm {
Text,
Integer,
}
impl StorageForm {
pub const ALL: [Self; 2] = [Self::Text, Self::Integer];
pub const fn as_str(self) -> &'static str {
match self {
Self::Text => "text",
Self::Integer => "integer",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Namespace {
Sqlite,
Postgres,
Mysql,
Mongo,
Graphql,
}
impl Namespace {
pub const ALL: [Self; 5] = [
Self::Sqlite,
Self::Postgres,
Self::Mysql,
Self::Mongo,
Self::Graphql,
];
pub const fn as_str(self) -> &'static str {
match self {
Self::Sqlite => "sqlite",
Self::Postgres => "postgres",
Self::Mysql => "mysql",
Self::Mongo => "mongo",
Self::Graphql => "graphql",
}
}
pub const fn database(self) -> Option<DatabaseKind> {
match self {
Self::Sqlite => Some(DatabaseKind::Sqlite),
Self::Postgres => Some(DatabaseKind::Postgres),
Self::Mysql => Some(DatabaseKind::Mysql),
Self::Mongo => Some(DatabaseKind::Mongo),
Self::Graphql => None,
}
}
pub const fn default_form(self) -> StorageForm {
match self {
Self::Sqlite | Self::Postgres | Self::Mysql | Self::Mongo => StorageForm::Integer,
Self::Graphql => StorageForm::Text,
}
}
pub const fn name_type(self) -> &'static str {
match self {
Self::Sqlite => "SqliteName",
Self::Postgres => "PostgresName",
Self::Mysql => "MysqlName",
Self::Mongo => "MongoName",
Self::Graphql => "GraphqlName",
}
}
pub fn accessor(self) -> syn::Ident {
format_ident!("as_{}_str", self.as_str())
}
pub fn default_name(self, canonical: &str) -> String {
match self {
Self::Sqlite | Self::Postgres | Self::Mysql | Self::Mongo => canonical.to_owned(),
Self::Graphql => canonical.to_shouty_snake_case(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum IntegerWidth {
I8,
I16,
I32,
I64,
U8,
U16,
U32,
}
impl IntegerWidth {
pub const ALL: [Self; 7] = [
Self::I8,
Self::I16,
Self::I32,
Self::I64,
Self::U8,
Self::U16,
Self::U32,
];
pub const DEFAULT: Self = Self::I64;
pub const UNCARRIED: [&'static str; 5] = ["u64", "u128", "i128", "usize", "isize"];
pub const fn as_str(self) -> &'static str {
match self {
Self::I8 => "i8",
Self::I16 => "i16",
Self::I32 => "i32",
Self::I64 => "i64",
Self::U8 => "u8",
Self::U16 => "u16",
Self::U32 => "u32",
}
}
pub fn named(word: &str) -> Option<Self> {
Self::ALL.into_iter().find(|width| width.as_str() == word)
}
pub fn is_repr_word(word: &str) -> bool {
Self::named(word).is_some() || Self::UNCARRIED.contains(&word)
}
pub const fn wire(self, database: DatabaseKind) -> Self {
match database {
DatabaseKind::Postgres => match self {
Self::I8 | Self::U8 => Self::I16,
Self::U16 => Self::I32,
Self::U32 => Self::I64,
Self::I16 | Self::I32 | Self::I64 => self,
},
DatabaseKind::Sqlite | DatabaseKind::Mysql | DatabaseKind::Mongo => self,
}
}
}
#[derive(Debug, Clone)]
pub struct EnumVariant {
pub ident: syn::Ident,
pub rename: Option<String>,
pub names: BTreeMap<Namespace, String>,
pub upstream: Option<syn::Ident>,
pub escape: Option<Escape>,
pub carrier: Option<syn::Type>,
}
#[derive(Debug, Clone)]
pub enum Escape {
Total,
Gate(syn::Path),
TryGate(syn::Path),
}
impl Escape {
#[must_use]
pub const fn gate(&self) -> Option<&syn::Path> {
match self {
Self::Total => None,
Self::Gate(path) | Self::TryGate(path) => Some(path),
}
}
#[must_use]
pub const fn refuses(&self) -> bool {
matches!(self, Self::TryGate(_))
}
}
impl EnumVariant {
pub fn canonical(&self) -> String {
use syn::ext::IdentExt as _;
self
.rename
.clone()
.unwrap_or_else(|| self.ident.unraw().to_string())
}
pub fn name(&self, namespace: Namespace) -> String {
self
.names
.get(&namespace)
.cloned()
.unwrap_or_else(|| namespace.default_name(&self.canonical()))
}
pub fn folded(&self) -> String {
use syn::ext::IdentExt as _;
self
.rename
.clone()
.unwrap_or_else(|| self.ident.unraw().to_string().to_snake_case())
}
pub fn predicate(&self) -> syn::Ident {
use syn::ext::IdentExt as _;
format_ident!("is_{}", self.ident.unraw().to_string().to_snake_case())
}
pub fn upstream(&self) -> syn::Ident {
self.upstream.clone().unwrap_or_else(|| self.ident.clone())
}
}
#[derive(Debug, Clone)]
pub struct Remote {
pub path: syn::Path,
pub delegates: Vec<Delegate>,
}
pub use crate::delegate::{Delegate, DelegateSkin};
pub const TEXT_FIELD: &str = "text";
#[derive(Debug, Clone)]
pub struct EnumModel {
pub krate: syn::Path,
pub vis: syn::Visibility,
pub name: syn::Ident,
pub width: Option<IntegerWidth>,
pub variants: Vec<EnumVariant>,
pub forms: BTreeMap<Namespace, StorageForm>,
pub wire_name: Option<String>,
pub error: Option<syn::Ident>,
pub remote: Option<Remote>,
}
impl EnumModel {
#[must_use]
pub fn form(&self, namespace: Namespace) -> StorageForm {
self
.forms
.get(&namespace)
.copied()
.unwrap_or_else(|| namespace.default_form())
}
#[must_use]
pub fn width(&self) -> IntegerWidth {
self.width.unwrap_or(IntegerWidth::DEFAULT)
}
#[must_use]
pub fn error(&self) -> syn::Ident {
self
.error
.clone()
.unwrap_or_else(|| format_ident!("{}ParseError", self.name))
}
#[must_use]
pub fn escape(&self) -> Option<&EnumVariant> {
self
.variants
.iter()
.find(|variant| variant.escape.is_some())
}
#[must_use]
pub fn posture(&self) -> Option<&Escape> {
self.escape().and_then(|variant| variant.escape.as_ref())
}
#[must_use]
pub fn refuses(&self) -> bool {
self.posture().is_none_or(Escape::refuses)
}
pub fn restated(&self) -> impl Iterator<Item = &EnumVariant> {
self
.variants
.iter()
.filter(|variant| variant.escape.is_none())
}
pub fn promoted(&self, kind: GraphqlKind) -> impl Iterator<Item = &Delegate> {
self
.remote
.iter()
.flat_map(|remote| remote.delegates.iter())
.filter(move |delegate| delegate.wire.iter().any(|skin| skin.kind == kind))
}
#[must_use]
pub fn emitted_methods(&self) -> Vec<Emitted> {
let Some(remote) = self.remote.as_ref() else {
return Vec::new();
};
let fixed = [
(format_ident!("VARIANTS"), Origin::Roster),
(format_ident!("remote"), Origin::Materialization),
];
let predicates = self.variants.iter().map(|variant| {
(
variant.predicate(),
Origin::Predicate(variant.ident.clone()),
)
});
let delegated = remote.delegates.iter().map(|delegate| {
let method = delegate.signature.ident.clone();
(method.clone(), Origin::Delegate(method))
});
fixed
.into_iter()
.chain(predicates)
.chain(delegated)
.map(|(name, origin)| Emitted {
owner: Owner::Record,
owner_name: self.name.clone(),
name,
origin,
})
.collect()
}
#[must_use]
pub fn emit(&self) -> proc_macro2::TokenStream {
if let Some(remote) = self.remote.as_ref() {
return self.emit_mirror(remote);
}
if let Some(escape) = self.escape() {
return self.emit_open(escape);
}
let error = self.refusal();
let reading = self.reading();
let face = self.face();
let parsing = self.parsing();
let key = self.key_delegation();
let storage = DatabaseKind::ALL
.into_iter()
.map(|database| self.storage_rows(database));
let width = self.width_row();
let read = self.read_row();
let wire = self.graphql_face();
quote! {
#error
const _: () = {
#reading
#face
#parsing
#key
#width
#read
#(#storage)*
};
#wire
}
}
fn key_delegation(&self) -> proc_macro2::TokenStream {
if let Some(escape) = self.escape() {
return self.open_key_delegation(escape);
}
let name = &self.name;
let delegates = self.framework(&["id"], "DelegatesId");
let text = self.framework(&["smol_bytes"], "Utf8Bytes");
let arms = self.variants.iter().map(|variant| {
let ident = &variant.ident;
let word = variant.canonical();
quote! {
Self::#ident => {
static __INGRAPH_WORD: ::std::sync::LazyLock<#text> =
::std::sync::LazyLock::new(|| <#text>::from_static(#word));
::std::sync::LazyLock::force(&__INGRAPH_WORD)
}
}
});
quote! {
#[automatically_derived]
unsafe impl #delegates for #name {
type Inner = #text;
#[inline]
fn delegate(&self) -> &#text {
match self {
#(#arms)*
}
}
}
}
}
fn open_key_delegation(&self, escape: &EnumVariant) -> proc_macro2::TokenStream {
let Some(carrier) = escape.carrier.as_ref() else {
return quote!();
};
let name = &self.name;
let escaped = &escape.ident;
let delegates = self.framework(&["id"], "DelegatesId");
let mirrors = self.remote.is_some();
let arms = self
.restated()
.map(|variant| {
let ident = &variant.ident;
let word = if mirrors {
variant.canonical()
} else {
variant.folded()
};
quote! {
Self::#ident => {
static __INGRAPH_WORD: ::std::sync::LazyLock<#carrier> = ::std::sync::LazyLock::new(
|| <#carrier as __IngraphCarriesAWord>::__ingraph_word(#word),
);
::std::sync::LazyLock::force(&__INGRAPH_WORD)
}
}
})
.collect::<Vec<_>>();
let obligation = (!arms.is_empty()).then(|| self.carrier_obligation());
quote! {
#obligation
#[automatically_derived]
unsafe impl #delegates for #name {
type Inner = #carrier;
#[inline]
fn delegate(&self) -> &#carrier {
match self {
#(#arms)*
Self::#escaped(__ingraph_word) => __ingraph_word,
}
}
}
}
}
fn carrier_obligation(&self) -> proc_macro2::TokenStream {
let name = &self.name;
let message = "`{Self}` cannot carry an `#[ingraph(other)]` escape's word";
let carrier = format!(
"an escape holds a WORD, so its field's type has to be a TEXT CARRIER: buildable from one \
(`From<&str>`) and readable back as one (`AsRef<str>`). `ingraph::Utf8Bytes` is the house's, \
and `String` and `SmolStr` are carriers too — `{name}`'s escape is where the choice is \
written, and it is the whole of what this vocabulary asks of it"
);
let key = "the bound is spent by the KEY row, which is what lets a vocabulary stand at an \
`#[ingraph(id)]` or an aggregate's group column with no extra word: the named \
members delegate to `static`s of the carrier and the escape delegates the word it \
carries, so the carrier is also what such a key ADDRESSES by. A text carrier that is \
not a member of the sealed id vocabulary compiles here and is refused at the KEY \
POSITION instead — see `ingraph::Id`";
quote! {
#[diagnostic::on_unimplemented(
message = #message,
label = "not a text carrier",
note = #carrier,
note = #key,
)]
trait __IngraphCarriesAWord {
fn __ingraph_word(word: &'static ::core::primitive::str) -> Self;
}
#[diagnostic::do_not_recommend]
impl<T: ::core::convert::From<&'static ::core::primitive::str>> __IngraphCarriesAWord for T {
#[inline]
fn __ingraph_word(word: &'static ::core::primitive::str) -> Self {
::core::convert::From::from(word)
}
}
}
}
fn width_row(&self) -> proc_macro2::TokenStream {
let name = &self.name;
let column_kind = self.framework(&["column"], "ColumnKind");
let column_eq = self.framework(&["column"], "ColumnEq");
quote! {
#[automatically_derived]
impl #column_kind for #name {}
#[automatically_derived]
impl #column_eq for #name {
#[inline]
fn column_eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
::core::cmp::PartialEq::eq(self, __ingraph_other)
}
}
}
}
fn read_row(&self) -> proc_macro2::TokenStream {
let name = &self.name;
let gate = self.framework(&["gate"], "if_sqlx");
let assemble = self.framework(&["column"], "Assemble");
let plain_column = self.framework(&["column"], "plain_column");
let path = self.framework(&["comparison"], "Path");
let row_trait = self.framework(&["sqlx"], "Row");
let decode = self.framework(&["sqlx"], "Decode");
let sqlx_type = self.framework(&["sqlx"], "Type");
let column_index = self.framework(&["sqlx"], "ColumnIndex");
let result = self.framework(&["sqlx"], "Result");
let row = crate::emit::parameter("ROW");
quote! {
#gate! {
#[automatically_derived]
impl<'__ingraph, #row> #assemble<'__ingraph, #row> for #name
where
#row: #row_trait,
#name: #decode<'__ingraph, <#row as #row_trait>::Database>
+ #sqlx_type<<#row as #row_trait>::Database>,
for<'__ingraph_name> &'__ingraph_name ::core::primitive::str: #column_index<#row>,
{
#[inline]
fn assemble(
__row: &'__ingraph #row,
__ingraph_under: ::core::option::Option<&#path<'_>>,
) -> #result<Self> {
#plain_column(__row, __ingraph_under)
}
}
}
}
}
fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
let krate = &self.krate;
let module = module.iter().map(|segment| format_ident!("{segment}"));
let name = format_ident!("{name}");
quote!(#krate::__private #(:: #module)* :: #name)
}
fn name_type(&self, namespace: Namespace) -> proc_macro2::TokenStream {
self.framework(&["name"], namespace.name_type())
}
fn refusal(&self) -> proc_macro2::TokenStream {
let vis = &self.vis;
let name = &self.name;
let error = self.error();
let sentence = format!("`{name}`: no variant answers to this name");
let doc = format!(
"The refusal a text that names no variant of [`{name}`] gets.\n\nOpaque: it carries no \
detail, because there is only one way to fail — the word is not one of this vocabulary's."
);
quote! {
#[doc = #doc]
#[derive(
::core::fmt::Debug,
::core::clone::Clone,
::core::marker::Copy,
::core::cmp::PartialEq,
::core::cmp::Eq
)]
#vis struct #error(());
#[automatically_derived]
impl ::core::fmt::Display for #error {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, #sentence)
}
}
#[automatically_derived]
impl ::core::error::Error for #error {}
}
}
fn reading(&self) -> proc_macro2::TokenStream {
let name = &self.name;
let markers = self.markers();
let cursor_value = self.framework(&["cursor"], "CursorValue");
let canonical = self.canonical_map();
quote! {
#markers
#[automatically_derived]
impl #cursor_value for #name {
fn write_cursor(&self, out: &mut ::std::vec::Vec<::core::primitive::u8>) {
out.extend_from_slice(Self::as_str(self).as_bytes());
}
fn read_cursor(bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
match ::core::str::from_utf8(bytes) {
::core::result::Result::Ok(text) => #canonical(text),
::core::result::Result::Err(_) => ::core::option::Option::None,
}
}
}
}
}
fn markers(&self) -> proc_macro2::TokenStream {
let name = &self.name;
let filter_marker = self.framework(&["marker"], "EnumFilterMarker");
let filter = self.framework(&["graphql"], "EnumFilter");
let default_marker = self.framework(&["marker"], "DefaultMarker");
let default_vec_marker = self.framework(&["marker"], "DefaultVecMarker");
let list_marker = self.framework(&["marker"], "ListMarker");
let marker = self.framework(&["marker"], "EnumMarker");
quote! {
#[automatically_derived]
impl #filter_marker for #name {
type Filter = #filter<#name>;
}
#[automatically_derived]
impl #default_marker for #name {
type Marker = #marker<#name>;
}
#[automatically_derived]
impl #default_vec_marker for #name {
type Marker = #list_marker<::std::vec::Vec<#name>, #marker<#name>>;
}
}
}
fn face(&self) -> proc_macro2::TokenStream {
let vis = &self.vis;
let name = &self.name;
let variants = self.variants.iter().map(|variant| {
let variant = &variant.ident;
quote!(Self::#variant)
});
let predicates = self.variants.iter().map(|variant| {
let ident = &variant.ident;
let predicate = variant.predicate();
let doc = format!("Whether this is [`{name}::{ident}`].");
quote! {
#[doc = #doc]
#[inline]
#[must_use]
#vis const fn #predicate(&self) -> ::core::primitive::bool {
::core::matches!(self, Self::#ident)
}
}
});
let canonical = self.arms(|variant| {
let word = variant.canonical();
quote!(#word)
});
let accessors = Namespace::ALL
.into_iter()
.filter(|namespace| self.form(*namespace) == StorageForm::Text)
.map(|namespace| self.accessor(namespace));
let variants_doc = format!(
"Every variant of [`{name}`], in DECLARATION order.\n\nThe order is the declaration's, so a \
schema rendered from this reads as the enum does."
);
let canonical_doc = format!(
"This variant's CANONICAL word — its global `rename`, else the name [`{name}`] spells it \
with.\n\nThe namespace [`FromStr`](core::str::FromStr) parses, and the one every face \
defaults from."
);
quote! {
#[automatically_derived]
impl #name {
#[doc = #variants_doc]
#vis const VARIANTS: &'static [Self] = &[#(#variants),*];
#[doc = #canonical_doc]
#[inline]
#[must_use]
#vis const fn as_str(&self) -> &'static ::core::primitive::str {
match self { #canonical }
}
#(#accessors)*
#(#predicates)*
}
}
}
fn accessor(&self, namespace: Namespace) -> proc_macro2::TokenStream {
let vis = &self.vis;
let accessor = namespace.accessor();
let name_type = self.name_type(namespace);
let arms = self.arms(|variant| {
let word = variant.name(namespace);
quote!(#word)
});
let doc = format!(
"This variant's word in the `{}` namespace.\n\nPresent because that face takes the TEXT \
form; a face storing the discriminant has none.",
namespace.as_str()
);
quote! {
#[doc = #doc]
#[inline]
#[must_use]
#vis const fn #accessor(&self) -> &'static #name_type {
#name_type::new(match self { #arms })
}
}
}
fn parsing(&self) -> proc_macro2::TokenStream {
let name = &self.name;
let error = self.error();
let canonical = self.canonical_map();
let canonical_map = self.reverse_map(&canonical, EnumVariant::canonical);
let texts: Vec<Namespace> = Namespace::ALL
.into_iter()
.filter(|namespace| self.form(*namespace) == StorageForm::Text)
.collect();
let maps = texts.iter().map(|namespace| {
self.reverse_map(&self.reader(*namespace), |variant| variant.name(*namespace))
});
let conversions = texts.iter().map(|namespace| self.conversion(*namespace));
quote! {
#canonical_map
#(#maps)*
#[automatically_derived]
impl ::core::str::FromStr for #name {
type Err = #error;
fn from_str(text: &::core::primitive::str) -> ::core::result::Result<Self, Self::Err> {
match #canonical(text) {
::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
::core::option::Option::None => ::core::result::Result::Err(#error(())),
}
}
}
#(#conversions)*
}
}
fn conversion(&self, namespace: Namespace) -> proc_macro2::TokenStream {
let name = &self.name;
let error = self.error();
let name_type = self.name_type(namespace);
let reader = self.reader(namespace);
quote! {
#[automatically_derived]
impl ::core::convert::TryFrom<&#name_type> for #name {
type Error = #error;
fn try_from(name: &#name_type) -> ::core::result::Result<Self, Self::Error> {
match #reader(name) {
::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
::core::option::Option::None => ::core::result::Result::Err(#error(())),
}
}
}
}
}
fn canonical_map(&self) -> syn::Ident {
format_ident!("__ingraph_of_canonical")
}
fn reader(&self, namespace: Namespace) -> syn::Ident {
format_ident!("__ingraph_of_{}", namespace.as_str())
}
fn reverse_map(
&self,
reader: &syn::Ident,
of: impl Fn(&EnumVariant) -> String,
) -> proc_macro2::TokenStream {
let name = &self.name;
let arms = self.variants.iter().map(|variant| {
let ident = &variant.ident;
let word = of(variant);
quote!(#word => ::core::option::Option::Some(#name::#ident),)
});
quote! {
fn #reader(text: &::core::primitive::str) -> ::core::option::Option<#name> {
match text {
#(#arms)*
_ => ::core::option::Option::None,
}
}
}
}
fn arms(
&self,
of: impl Fn(&EnumVariant) -> proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
let arms = self.variants.iter().map(|variant| {
let ident = &variant.ident;
let value = of(variant);
quote!(Self::#ident => #value,)
});
quote!(#(#arms)*)
}
fn storage_rows(&self, database: DatabaseKind) -> proc_macro2::TokenStream {
let Some(namespace) = Namespace::ALL
.into_iter()
.find(|namespace| namespace.database() == Some(database))
else {
return quote!();
};
if !database.is_sql() {
return quote!();
}
let name = &self.name;
let gate = self.framework(&["gate"], &database.gate().to_string());
let backend = self.backend(database);
let carrier = self.framework(&["comparison", "sql"], "Carrier");
let query_builder = self.framework(&["sqlx"], "QueryBuilder");
let sqlx_type = self.framework(&["sqlx"], "Type");
let encode = self.framework(&["sqlx"], "Encode");
let decode = self.framework(&["sqlx"], "Decode");
let database_trait = self.framework(&["sqlx"], "Database");
let is_null = self.framework(&["sqlx", "encode"], "IsNull");
let error = self.framework(&["sqlx", "error"], "BoxDynError");
let stored_as = self.framework(&["column"], "StoredAs");
let (stored, borrowed, maps, bind, of_stored, refused, declared) = match self.form(namespace) {
StorageForm::Text => {
let accessor = namespace.accessor();
let reader = self.reader(namespace);
(
quote!(::core::primitive::str),
quote!(&'__ingraph ::core::primitive::str),
quote!(),
quote!({
let stored: &'static ::core::primitive::str = #name::#accessor(self);
stored
}),
quote!(#reader(stored)),
format!("{name}: the stored text names no variant of this enum"),
quote!(::std::string::String),
)
}
StorageForm::Integer => {
let width = self.width().wire(database);
let primitive = format_ident!("{}", width.as_str());
let stored_fn = format_ident!("__ingraph_{}_stored", namespace.as_str());
let of_stored_fn = format_ident!("__ingraph_{}_of_stored", namespace.as_str());
(
quote!(::core::primitive::#primitive),
quote!(::core::primitive::#primitive),
self.integer_maps(&stored_fn, &of_stored_fn, &primitive),
quote!(#stored_fn(self)),
quote!(#of_stored_fn(stored)),
format!("{name}: the stored discriminant names no variant of this enum"),
quote!(::core::primitive::#primitive),
)
}
};
quote! {
#gate! {
#maps
#[automatically_derived]
impl #sqlx_type<#backend> for #name {
fn type_info() -> <#backend as #database_trait>::TypeInfo {
<#stored as #sqlx_type<#backend>>::type_info()
}
fn compatible(ty: &<#backend as #database_trait>::TypeInfo) -> ::core::primitive::bool {
<#stored as #sqlx_type<#backend>>::compatible(ty)
}
}
#[automatically_derived]
impl<'__ingraph> #encode<'__ingraph, #backend> for #name {
fn encode_by_ref(
&self,
buf: &mut <#backend as #database_trait>::ArgumentBuffer,
) -> ::core::result::Result<#is_null, #error> {
<#borrowed as #encode<'__ingraph, #backend>>::encode(#bind, buf)
}
}
#[automatically_derived]
impl<'__ingraph> #decode<'__ingraph, #backend> for #name {
fn decode(
value: <#backend as #database_trait>::ValueRef<'__ingraph>,
) -> ::core::result::Result<Self, #error> {
let stored = <#borrowed as #decode<'__ingraph, #backend>>::decode(value)?;
match #of_stored {
::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
::core::option::Option::None => ::core::result::Result::Err(#error::from(#refused)),
}
}
}
#[automatically_derived]
impl #stored_as<#backend> for #name {
const WORDS: &'static [&'static ::core::primitive::str] =
<#declared as #stored_as<#backend>>::WORDS;
}
#[automatically_derived]
impl #carrier<#backend> for #name {
fn push_bind(&self, qb: &mut #query_builder<#backend>) {
qb.push_bind(#bind);
}
}
}
}
}
fn backend(&self, database: DatabaseKind) -> proc_macro2::TokenStream {
match database {
DatabaseKind::Sqlite => self.framework(&["sqlx"], "Sqlite"),
DatabaseKind::Postgres => self.framework(&["sqlx"], "Postgres"),
DatabaseKind::Mysql => self.framework(&["sqlx"], "MySql"),
DatabaseKind::Mongo => self.framework(&["comparison", "mongo"], "Mongo"),
}
}
fn integer_maps(
&self,
stored: &syn::Ident,
of_stored: &syn::Ident,
primitive: &syn::Ident,
) -> proc_macro2::TokenStream {
let name = &self.name;
let forward = self.variants.iter().map(|variant| {
let ident = &variant.ident;
quote!(#name::#ident => #name::#ident as ::core::primitive::#primitive)
});
let reverse = self.variants.iter().map(|variant| {
let ident = &variant.ident;
quote! {
value if value == #name::#ident as ::core::primitive::#primitive => {
::core::option::Option::Some(#name::#ident)
}
}
});
quote! {
fn #stored(value: &#name) -> ::core::primitive::#primitive {
match value {
#(#forward,)*
}
}
fn #of_stored(
value: ::core::primitive::#primitive,
) -> ::core::option::Option<#name> {
match value {
#(#reverse,)*
_ => ::core::option::Option::None,
}
}
}
}
}