use quote::{format_ident, quote};
use crate::{
emit::{leading, parameter},
interface::InterfaceModel,
model::DatabaseKind,
};
impl InterfaceModel {
pub(crate) fn output(&self) -> proc_macro2::TokenStream {
let vis = &self.vis;
let interface = &self.name;
let name = super::default_output_name(interface);
let transformer = self.framework(&["transform"], "Transformer");
let graphql = self.framework(&["transform"], "Graphql");
let variants = self.members.iter().map(|member| {
let (variant, ty) = (&member.ident, &member.ty);
let doc = leading(&format!(
"A [`{}`], as that member's own declaration publishes it.",
quote!(#ty)
));
quote! {
#[doc = #doc]
#variant(<<#ty as #transformer>::Graphql as #graphql>::Output),
}
});
let doc = leading(&format!(
"One answer to a query over [`{interface}`] — whichever member the row came from, as that \
member's own wire object.\n\nThe payload is reached as a family projection and never as a \
name this crate builds, so a member that renames its output moves this variant with it."
));
quote! {
#[doc = #doc]
#[derive(::core::fmt::Debug, ::core::clone::Clone)]
#vis enum #name {
#(#variants)*
}
}
}
pub(crate) fn hydration(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
let vis = &self.vis;
let interface = &self.name;
let vocabulary = super::default_kind_name(interface);
let address = super::default_id_name(interface);
let output = super::default_output_name(interface);
let error = self.hydration_error(kind);
let record = self.framework(&["transform"], "Record");
let transformer = self.framework(&["transform"], "Transformer");
let graphql = self.framework(&["transform"], "Graphql");
let sql_query = self.framework(&["query", "sql"], "SqlQuery");
let rows = self.framework(&["query", "sql"], "rows");
let begin_read = self.framework(&["query", "sql"], "BeginRead");
let hydration_error = self.framework(&["interface"], "HydrationError");
let acquire = self.framework(&["sqlx"], "Acquire");
let capability = self.framework(&["interface"], "InterfaceKind");
let query_error = self.framework(&["query", "sql"], "SqlQueryError");
let crossing = self.framework(&["query", "sql"], "CrossingError");
let (module, item) = kind.backend();
let backend = self.framework(module, item);
let executor = parameter("EXEC");
let interface_name = interface.to_string();
let arms = self.members.iter().map(|member| {
let (variant, ty) = (&member.ident, &member.ty);
let word = crate::union::word(&member.ident).to_string();
let row = quote!(<#ty as #record<#backend>>::Row);
let member_output = quote!(<<#ty as #transformer>::Graphql as #graphql>::Output);
quote! {
#vocabulary::#variant => {
let mut __ingraph_asked = ::std::vec::Vec::with_capacity(<[#address]>::len(ids));
for __ingraph_address in ids {
match __ingraph_address {
#address::#variant(__ingraph_id) => ::std::vec::Vec::push(
&mut __ingraph_asked,
::core::clone::Clone::clone(__ingraph_id),
),
__ingraph_other => {
let __ingraph_why = #hydration_error::Foreign {
interface: #interface_name,
asked: #word,
held: #capability::as_str(#address::kind(__ingraph_other)),
};
return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
}
}
}
let __ingraph_rows: ::std::vec::Vec<#row> =
match #rows::<#row, #backend, #executor>(executor, &__ingraph_asked).await {
::core::result::Result::Ok(__ingraph_rows) => __ingraph_rows,
::core::result::Result::Err(__ingraph_why) => {
let __ingraph_why: #query_error = __ingraph_why;
return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
}
};
let mut __ingraph_found: ::std::vec::Vec<::core::option::Option<#output>> =
::std::vec::Vec::with_capacity(<[#address]>::len(ids));
for _ in 0..<[#address]>::len(ids) {
::std::vec::Vec::push(&mut __ingraph_found, ::core::option::Option::None);
}
for __ingraph_row in __ingraph_rows {
let __ingraph_id = match #sql_query::<#backend>::id(&__ingraph_row) {
::core::result::Result::Ok(__ingraph_id) => #address::#variant(__ingraph_id),
::core::result::Result::Err(__ingraph_why) => {
let __ingraph_why: #crossing = __ingraph_why;
return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
}
};
let ::core::option::Option::Some(__ingraph_at) =
<[#address]>::iter(ids).position(|__ingraph_held| *__ingraph_held == __ingraph_id)
else {
continue;
};
let __ingraph_raised = match <#member_output as ::core::convert::TryFrom<#row>>::try_from(
__ingraph_row,
) {
::core::result::Result::Ok(__ingraph_raised) => __ingraph_raised,
::core::result::Result::Err(__ingraph_why) => {
let __ingraph_why:
<#member_output as ::core::convert::TryFrom<#row>>::Error = __ingraph_why;
return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
}
};
__ingraph_found[__ingraph_at] =
::core::option::Option::Some(#output::#variant(__ingraph_raised));
}
let __ingraph_missing = ::core::iter::Iterator::count(::core::iter::Iterator::filter(
<[::core::option::Option<#output>]>::iter(&__ingraph_found),
|__ingraph_slot| ::core::option::Option::is_none(*__ingraph_slot),
));
if __ingraph_missing > 0 {
let __ingraph_why = #hydration_error::Missing {
interface: #interface_name,
member: #word,
missing: __ingraph_missing,
};
return ::core::result::Result::Err(::core::convert::Into::into(__ingraph_why));
}
::core::result::Result::Ok(::core::iter::Iterator::collect(
::core::iter::Iterator::flatten(::std::vec::Vec::into_iter(__ingraph_found)),
))
}
}
});
let name = format_ident!("hydrate_{}", kind.as_str());
let doc = leading(&format!(
"Read `kind`'s member's rows at `ids` out of {what}, each as that member's own wire \
object.\n\nThe answer is in the order `ids` were asked in, which for a page's caller is the \
statement's — a gather answers in the engine's order and every row is asked for its own \
address to be put back.\n\nHanded the same `&mut Transaction` the page ran on, this sees \
exactly the rows that page answered with; handed a pool it opens a read of its own, and the \
gap between the two moments is what the coherence refusal reports.",
what = super::row::what(kind)
));
let errors_doc = leading(&format!(
"# Errors\n[`{error}`] — a driver refusal, a member's own row-to-wire crossing, an address of \
another member, or rows the union answered with that this member's table no longer holds.",
error = super::contract::tight(&error)
));
quote! {
impl #interface {
#[doc = #doc]
#[doc = ""]
#[doc = #errors_doc]
#vis async fn #name<'__ingraph_c, #executor>(
kind: #vocabulary,
ids: &[#address],
executor: #executor,
) -> ::core::result::Result<::std::vec::Vec<#output>, #error>
where
#executor: #acquire<'__ingraph_c, Database = #backend> + #begin_read,
{
use #capability as _;
match kind {
#(#arms)*
}
}
}
}
}
}