use quote::{format_ident, quote};
use crate::{
emit::{leading, parameter},
interface::{InterfaceField, InterfaceModel},
model::DatabaseKind,
unit,
};
const KIND_VARIANT: &str = "__IgKind";
const ADDRESS_VARIANT: &str = "__IgAddress";
impl InterfaceModel {
#[must_use]
pub fn cursor_name(&self, kind: DatabaseKind) -> syn::Ident {
format_ident!("{}{}Cursor", self.name, kind.suffix())
}
#[must_use]
pub fn comparison_name(&self, kind: DatabaseKind) -> syn::Ident {
format_ident!("{}{}Comparison", self.name, kind.suffix())
}
pub(crate) fn page(&self) -> proc_macro2::TokenStream {
if !self.projects() {
return quote!();
}
let address = self.address_carrier();
let databases = self.sql_databases().into_iter().map(|kind| {
let cursor = self.cursor_value(kind);
let comparison = self.comparison(kind);
quote! {
#cursor
#comparison
}
});
quote! {
#address
#(#databases)*
}
}
fn address_carrier(&self) -> proc_macro2::TokenStream {
let name = super::default_id_name(&self.name);
let identifiable = self.framework(&["transform"], "Identifiable");
let cursor_value = self.framework(&["cursor"], "CursorValue");
let carrier = self.framework(&["comparison", "sql"], "Carrier");
let database = self.framework(&["sqlx"], "Database");
let held = self.framework(&["sqlx"], "QueryBuilder");
let db = parameter("DB");
let writes = self.members.iter().enumerate().map(|(tag, member)| {
let variant = &member.ident;
let tag = u8::try_from(tag).unwrap_or(u8::MAX);
quote! {
Self::#variant(__ingraph_value) => {
__ingraph_out.push(#tag);
#cursor_value::write_cursor(__ingraph_value, __ingraph_out);
}
}
});
let reads = self.members.iter().enumerate().map(|(tag, member)| {
let (variant, ty) = (&member.ident, &member.ty);
let tag = u8::try_from(tag).unwrap_or(u8::MAX);
quote! {
#tag => ::core::option::Option::map(
<<#ty as #identifiable>::Id as #cursor_value>::read_cursor(__ingraph_rest),
Self::#variant,
),
}
});
let binds = self.members.iter().map(|member| {
let variant = &member.ident;
quote!(Self::#variant(__ingraph_value) => #carrier::push_bind(__ingraph_value, __ingraph_qb),)
});
let codecs = self.members.iter().map(|member| {
let ty = &member.ty;
quote!(<#ty as #identifiable>::Id: #cursor_value,)
});
let bounds = self.members.iter().map(|member| {
let ty = &member.ty;
quote!(<#ty as #identifiable>::Id: #carrier<#db>,)
});
let write_doc = leading("Append this address's member tag and that member's own id bytes.");
let read_doc = leading("The address `bytes` hold, or `None` where they name no member.");
let bind_doc = leading("Bind this address, in the type its own member's table stores.");
quote! {
#[automatically_derived]
impl #cursor_value for #name
where
#(#codecs)*
{
#[doc = #write_doc]
fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
match self {
#(#writes)*
}
}
#[doc = #read_doc]
fn read_cursor(__ingraph_bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
let (__ingraph_tag, __ingraph_rest) =
<[::core::primitive::u8]>::split_first(__ingraph_bytes)?;
match *__ingraph_tag {
#(#reads)*
_ => ::core::option::Option::None,
}
}
}
#[automatically_derived]
impl<#db> #carrier<#db> for #name
where
#db: #database,
#(#bounds)*
{
#[doc = #bind_doc]
fn push_bind(&self, __ingraph_qb: &mut #held<#db>) {
match self {
#(#binds)*
}
}
}
}
}
fn cursor_value(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
let vis = &self.vis;
let interface = &self.name;
let name = self.cursor_name(kind);
let vocabulary = super::default_kind_name(interface);
let address = super::default_id_name(interface);
let kind_variant = format_ident!("{KIND_VARIANT}");
let address_variant = format_ident!("{ADDRESS_VARIANT}");
let cursor_value = self.framework(&["cursor"], "CursorValue");
let dialect_cursor = self.framework(&["cursor"], "DialectCursor");
let (module, item) = kind.dialect();
let backend = self.framework(module, item);
let carrier = self.framework(&["comparison", "sql"], "Carrier");
let capability = self.framework(&["interface"], "InterfaceKind");
let database = self.framework(&["sqlx"], "Database");
let held = self.framework(&["sqlx"], "QueryBuilder");
let db = parameter("DB");
let stored: Vec<&InterfaceField> = self.projected().collect();
let variants = stored.iter().map(|field| {
let variant = variant_of(field);
let ty = self.stored_at(field, kind);
let doc = leading(&format!("The `{}` column's value.", field.name));
quote! {
#[doc = #doc]
#variant(#ty),
}
});
let writes = stored.iter().enumerate().map(|(tag, field)| {
let variant = variant_of(field);
let ty = self.stored_at(field, kind);
let tag = u8::try_from(tag).unwrap_or(u8::MAX);
quote! {
Self::#variant(__ingraph_value) => {
__ingraph_out.push(#tag);
<#ty as #dialect_cursor<#backend>>::write_cursor_at(__ingraph_value, __ingraph_out);
}
}
});
let reads = stored.iter().enumerate().map(|(tag, field)| {
let variant = variant_of(field);
let ty = self.stored_at(field, kind);
let tag = u8::try_from(tag).unwrap_or(u8::MAX);
quote! {
#tag => ::core::option::Option::map(
<#ty as #dialect_cursor<#backend>>::read_cursor_at(__ingraph_rest),
Self::#variant,
),
}
});
let binds = stored.iter().map(|field| {
let variant = variant_of(field);
quote!(Self::#variant(__ingraph_value) => #carrier::push_bind(__ingraph_value, __ingraph_qb),)
});
let codecs = stored.iter().map(|field| {
let ty = self.stored_at(field, kind);
quote!(#ty: #dialect_cursor<#backend>,)
});
let bounds = stored.iter().map(|field| {
let ty = self.stored_at(field, kind);
quote!(#ty: #carrier<#db>,)
});
let kind_tag = u8::try_from(stored.len()).unwrap_or(u8::MAX);
let address_tag = kind_tag.saturating_add(1);
let what = super::row::what(kind);
let doc = leading(&format!(
"One slot of a cursor over a page of [`{interface}`] in {what} — which column, and the value \
it held at the boundary row.\n\nThe last two are the framework's own: an interface's total \
order ends `…, __ig_kind__, id`, because an id is `UNIQUE` only within its own member's \
table and the discriminant is what tells two members' rows apart."
));
let kind_doc = leading(
"The DISCRIMINANT the boundary row carried. Minted from the address rather than carried \
beside it, so the pair cannot disagree.",
);
let address_doc =
leading("The boundary row's ADDRESS — which member, and that member's own id.");
let write_doc = leading("Append this slot's tag and its value's own bytes.");
let read_doc = leading("The slot `bytes` hold, or `None` where they name no column.");
let bind_doc = leading("Bind this slot's value, in the type this database stores.");
quote! {
#[doc = #doc]
#[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
#vis enum #name {
#(#variants)*
#[doc = #kind_doc]
#kind_variant(#vocabulary),
#[doc = #address_doc]
#address_variant(#address),
}
#[automatically_derived]
impl #cursor_value for #name
where
#(#codecs)*
#address: #cursor_value,
{
#[doc = #write_doc]
fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
match self {
#(#writes)*
Self::#kind_variant(__ingraph_value) => {
__ingraph_out.push(#kind_tag);
#cursor_value::write_cursor(
&::std::borrow::ToOwned::to_owned(#capability::as_str(*__ingraph_value)),
__ingraph_out,
);
}
Self::#address_variant(__ingraph_value) => {
__ingraph_out.push(#address_tag);
#cursor_value::write_cursor(__ingraph_value, __ingraph_out);
}
}
}
#[doc = #read_doc]
fn read_cursor(__ingraph_bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
let (__ingraph_tag, __ingraph_rest) =
<[::core::primitive::u8]>::split_first(__ingraph_bytes)?;
match *__ingraph_tag {
#(#reads)*
#kind_tag => ::core::option::Option::map(
::core::result::Result::ok(<#vocabulary as #capability>::parse(
&<::std::string::String as #cursor_value>::read_cursor(__ingraph_rest)?,
)),
Self::#kind_variant,
),
#address_tag => ::core::option::Option::map(
<#address as #cursor_value>::read_cursor(__ingraph_rest),
Self::#address_variant,
),
_ => ::core::option::Option::None,
}
}
}
#[automatically_derived]
impl<#db> #carrier<#db> for #name
where
#db: #database,
#(#bounds)*
::std::string::String: #carrier<#db>,
#address: #carrier<#db>,
{
#[doc = #bind_doc]
fn push_bind(&self, __ingraph_qb: &mut #held<#db>) {
match self {
#(#binds)*
Self::#kind_variant(__ingraph_value) => #carrier::push_bind(
&::std::borrow::ToOwned::to_owned(#capability::as_str(*__ingraph_value)),
__ingraph_qb,
),
Self::#address_variant(__ingraph_value) =>
#carrier::push_bind(__ingraph_value, __ingraph_qb),
}
}
}
}
}
fn comparison(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
let interface = &self.name;
let name = self.comparison_name(kind);
let db = parameter("DB");
let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
let crossings = self.crossings(kind);
let rows: Vec<unit::ComparisonColumn> = self
.stored()
.map(|field| {
let (filter, stored) = (self.filter_of(field), self.stored_at(field, kind));
unit::ComparisonColumn {
gate: proc_macro2::TokenStream::new(),
member: field.name.clone(),
name: format!("shared `{}` column", field.name),
held: quote!(<#filter as #to_comparison<#stored, #db>>::Comparison),
}
})
.collect();
let header = unit::UnitHeader {
vis: &self.vis,
name: name.clone(),
subject: format!("[`{interface}`]"),
note: Some(
"Written in the INTERFACE's vocabulary and lowered ONCE, above the union — a member that \
calls a shared column something else has already aliased it in its own arm, so one \
predicate answers whichever member the row came from."
.to_owned(),
),
};
let (declaration, methods) = unit::comparison(&header, &db, &crossings, &rows);
let seats = unit::LoweringSeats {
backend: self.framework(&["comparison"], "Backend"),
complex: self.framework(&["comparison"], "ComplexComparison"),
frame: self.framework(&["comparison"], "Frame"),
at: self.framework(&["comparison"], "At"),
field_name: self.framework(&["field"], "FieldName"),
};
let lowered: Vec<unit::LoweringColumn> = self
.projected()
.map(|field| unit::LoweringColumn {
gate: proc_macro2::TokenStream::new(),
member: field.name.clone(),
rendered: field.name.to_string(),
flatten: false,
through: None,
})
.collect();
let lowering = unit::comparison_lowering(&name, &db, &crossings, &seats, &lowered);
quote! {
#declaration
#methods
#lowering
}
}
fn crossings(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
let db = parameter("DB");
let backend = self.framework(&["comparison"], "Backend");
let to_comparison = self.framework(&["comparison"], "ToDatabaseComparison");
let crossings = self.stored().map(|field| {
let (filter, stored) = (self.filter_of(field), self.stored_at(field, kind));
quote!(#filter: #to_comparison<#stored, #db>,)
});
quote! {
#db: #backend,
#(#crossings)*
}
}
pub(super) fn filter_of(&self, field: &InterfaceField) -> proc_macro2::TokenStream {
crate::emit::filter_of(
&self.krate,
&field.ty,
field.marker.as_ref(),
crate::emit::FilterFace::Column,
)
}
}
fn variant_of(field: &InterfaceField) -> syn::Ident {
crate::emit::upper_camel(&field.name.to_string())
}