use quote::quote;
use crate::{
interface::InterfaceModel,
model::{DatabaseKind, default_queries_name},
};
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tower_tests;
impl InterfaceModel {
#[must_use]
pub fn published_plural(&self) -> String {
self
.plural
.clone()
.unwrap_or_else(|| crate::plural::of(&self.name.to_string()))
}
pub(crate) fn wire_query_database(&self) -> Option<DatabaseKind> {
if !self.projects() {
return None;
}
self.sql_databases().first().copied()
}
fn queries_type(&self) -> proc_macro2::TokenStream {
if self.wire_query_database().is_none() {
return quote!();
}
let vis = &self.vis;
let interface = &self.name;
let name = default_queries_name(interface);
let doc = crate::emit::leading(&format!(
"The root fields a [`{interface}`] answers — a page of them, across every member the contract \
declares.\n\nMounted by folding it into a graph's root query; it holds nothing and reads its \
store through the door the schema was built with. There is no by-id field here and that is a \
ruling rather than a gap: an interface's address is a SUM over its members' ids, so a row is \
fetched from the MEMBER's own root and `__typename` is what says which member to ask."
));
quote! {
#[doc = #doc]
#[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::marker::Copy, ::core::default::Default)]
#vis struct #name;
}
}
fn wire_binding(&self) -> proc_macro2::TokenStream {
if !self.projects() {
return quote!();
}
let interface = &self.name;
let input = super::default_input_name(interface);
let output = super::default_output_name(interface);
let filter = super::default_filter_name(interface);
let order_by = super::default_order_by_name(interface);
let face = self.framework(&["transform"], "Graphql");
let input_face = self.framework(&["transform"], "GraphqlInput");
let output_face = self.framework(&["transform"], "GraphqlOutput");
let queries = match self.wire_query_database() {
Some(_) => {
let name = default_queries_name(interface);
quote!(#name)
}
None => quote!(()),
};
quote! {
#[automatically_derived]
impl #input_face for #input {
type Filter = #filter;
type OrderBy = #order_by;
}
#[automatically_derived]
impl #output_face for #output {
type Key = ();
}
#[automatically_derived]
impl #face for #interface {
type Input = #input;
type Output = #output;
type Query = #queries;
}
}
}
fn page_names(&self) -> proc_macro2::TokenStream {
let ag = self.framework(&[], "async_graphql");
let interface = &self.name;
let base = crate::emit::raise_initial(&self.published_plural());
let marker = |declared: Option<&String>, suffix: &str, hook: &str, what: &str| {
let word = declared.map_or_else(|| format!("{base}{suffix}"), ToOwned::to_owned);
let name = quote::format_ident!("{interface}{suffix}Name");
let hook = self.framework(&["graphql"], hook);
let doc = crate::emit::leading(&format!(
"What the schema calls {what} of [`{interface}`]s — `{word}`.\n\nThe naming tower's word, \
resolved in one place: the base is this interface's PLURAL, `graphql(plural = \"…\")` \
covers it, and `graphql({suffix_word}(rename = \"…\"))` covers that. Tooling that finds a \
page by the NODE's stem rather than by its fields sees a name it does not recognise, which \
is the trade the plural base makes once for every declaration that has a page.",
suffix_word = suffix.to_lowercase(),
));
quote! {
#[doc = #doc]
struct #name;
impl #hook for #name {
fn type_name<__IngraphNode: #ag::OutputType>() -> ::std::string::String {
::std::borrow::ToOwned::to_owned(#word)
}
}
}
};
let connection = marker(
self.connection.as_ref(),
"Connection",
"ConnectionNameType",
"a page",
);
let edge = marker(self.edge.as_ref(), "Edge", "EdgeNameType", "one edge");
quote!(#connection #edge)
}
fn list_leg(&self, kind: DatabaseKind) -> proc_macro2::TokenStream {
let interface = &self.name;
let ag = self.framework(&[], "async_graphql");
let door = self.framework(&["graphql"], "SqlDoor");
let orderings = self.framework(&["graphql"], "Orderings");
let connection = self.framework(&["graphql"], "Connection");
let page_request = self.framework(&["graphql"], "PageRequest");
let refused = self.framework(&["graphql"], "refused");
let refused_filter = self.framework(&["graphql"], "refused_filter");
let refused_row = self.framework(&["graphql"], "refused_row");
let try_from_filter = self.framework(&["comparison"], "TryFromFilter");
let capability = self.framework(&["interface"], "InterfaceKind");
let page_ty = self.framework(&["query"], "Page");
let edge_ty = self.framework(&["query"], "Edge");
let vocabulary = super::default_kind_name(interface);
let address = super::default_id_name(interface);
let output = super::default_output_name(interface);
let row = super::default_row_name(interface, kind);
let cursor = self.cursor_name(kind);
let comparison = self.comparison_name(kind);
let filter = super::default_filter_name(interface);
let order_by = super::default_order_by_name(interface);
let (module, item) = kind.backend();
let backend = self.framework(module, item);
let hydrate = quote::format_ident!("hydrate_{}", kind.as_str());
let finder = kind.finder();
let field = crate::emit::lower_initial(&self.published_plural());
let method = crate::method::wire_method("e::format_ident!(
"{}_list",
crate::emit::snake(&interface.to_string())
));
let ctx = crate::method::wire_method("e::format_ident!("ctx"));
let (order, first, last, after, before) = (
crate::method::wire_method("e::format_ident!("order_by")),
crate::method::wire_method("e::format_ident!("first")),
crate::method::wire_method("e::format_ident!("last")),
crate::method::wire_method("e::format_ident!("after")),
crate::method::wire_method("e::format_ident!("before")),
);
let predicate = crate::method::wire_method("e::format_ident!("where"));
let arity = crate::emit::wide_signature();
let connection_name = quote::format_ident!("{interface}ConnectionName");
let edge_name = quote::format_ident!("{interface}EdgeName");
quote! {
#[graphql(name = #field)]
#arity
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#[graphql(name = "orderBy")] #order: ::core::option::Option<#orderings<#order_by>>,
#[graphql(name = "first")] #first: ::core::option::Option<u32>,
#[graphql(name = "last")] #last: ::core::option::Option<u32>,
#[graphql(name = "after")] #after: ::core::option::Option<::std::string::String>,
#[graphql(name = "before")] #before: ::core::option::Option<::std::string::String>,
#[graphql(name = "where")] #predicate: ::core::option::Option<#filter>,
) -> #ag::Result<#connection<#output, #cursor, #connection_name, #edge_name>> {
let __ingraph_door = #ag::Context::data::<#door<#backend>>(#ctx)?;
let __ingraph_predicate = match #predicate {
::core::option::Option::Some(__ingraph_written) => ::core::option::Option::Some(
<#comparison<#backend> as #try_from_filter<#filter>>::try_from_filter(__ingraph_written)
.map_err(|__ingraph_refusal| #refused_filter(&__ingraph_refusal))?,
),
::core::option::Option::None => ::core::option::Option::None,
};
let __ingraph_request = <#page_request<#cursor>>::of(
#first,
#last,
::core::option::Option::as_deref(&#after),
::core::option::Option::as_deref(&#before),
)
.map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
let __ingraph_terms: ::std::vec::Vec<#order_by> = ::core::iter::Iterator::collect(
::core::iter::Iterator::cloned(
#orderings::terms(&::core::option::Option::unwrap_or_default(#order)),
),
);
let __ingraph_found = #interface::#finder(#door::pool(__ingraph_door));
let __ingraph_found = match &__ingraph_predicate {
::core::option::Option::Some(__ingraph_narrowing) => {
__ingraph_found.filter(__ingraph_narrowing)
}
::core::option::Option::None => __ingraph_found,
};
let __ingraph_found = __ingraph_found.order(&__ingraph_terms);
let __ingraph_page: #page_ty<#row, #cursor> = match &__ingraph_request {
#page_request::Forward { after: __ingraph_at, .. } => {
let __ingraph_walk = __ingraph_found.first(#page_request::size(&__ingraph_request));
match __ingraph_at {
::core::option::Option::Some(__ingraph_cursor) => {
__ingraph_walk.after(__ingraph_cursor).fetch().await
}
::core::option::Option::None => __ingraph_walk.fetch().await,
}
}
#page_request::Backward { before: __ingraph_at, .. } => {
let __ingraph_walk = __ingraph_found.last(#page_request::size(&__ingraph_request));
match __ingraph_at {
::core::option::Option::Some(__ingraph_cursor) => {
__ingraph_walk.before(__ingraph_cursor).fetch().await
}
::core::option::Option::None => __ingraph_walk.fetch().await,
}
}
}
.map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
let __ingraph_rows = #page_ty::edges(&__ingraph_page);
let mut __ingraph_nodes: ::std::vec::Vec<::core::option::Option<#output>> =
::std::vec::Vec::with_capacity(<[_]>::len(__ingraph_rows));
for _ in 0..<[_]>::len(__ingraph_rows) {
::std::vec::Vec::push(&mut __ingraph_nodes, ::core::option::Option::None);
}
for __ingraph_kind in <#vocabulary as #capability>::ALL {
let mut __ingraph_asked: ::std::vec::Vec<#address> = ::std::vec::Vec::new();
let mut __ingraph_slots: ::std::vec::Vec<usize> = ::std::vec::Vec::new();
for (__ingraph_at, __ingraph_edge) in
::core::iter::Iterator::enumerate(<[_]>::iter(__ingraph_rows))
{
let __ingraph_id = #row::id(#edge_ty::node(__ingraph_edge));
if #address::kind(__ingraph_id) != *__ingraph_kind {
continue;
}
::std::vec::Vec::push(
&mut __ingraph_asked,
::core::clone::Clone::clone(__ingraph_id),
);
::std::vec::Vec::push(&mut __ingraph_slots, __ingraph_at);
}
if ::std::vec::Vec::is_empty(&__ingraph_asked) {
continue;
}
let __ingraph_raised = #interface::#hydrate(
*__ingraph_kind,
&__ingraph_asked,
#door::pool(__ingraph_door),
)
.await
.map_err(|__ingraph_refusal| #refused_row(&__ingraph_refusal))?;
for (__ingraph_at, __ingraph_node) in ::core::iter::Iterator::zip(
::std::vec::Vec::into_iter(__ingraph_slots),
::std::vec::Vec::into_iter(__ingraph_raised),
) {
__ingraph_nodes[__ingraph_at] = ::core::option::Option::Some(__ingraph_node);
}
}
#page_ty::into_connection_of(__ingraph_page, __ingraph_nodes)
.map_err(|__ingraph_refusal| #refused_row(&__ingraph_refusal))
}
}
}
fn queries_face(&self) -> proc_macro2::TokenStream {
let Some(kind) = self.wire_query_database() else {
return quote!();
};
let name = default_queries_name(&self.name);
let sdl = name.to_string();
let ag = self.framework(&[], "async_graphql");
let shelf = crate::emit::vendored(&self.krate, "async_graphql");
let binding_gate = self.framework(&["gate"], "if_async_graphql");
let database_gate = self.framework(&["gate"], &kind.gate().to_string());
let prelude = crate::emit::wire::prelude();
let names = self.page_names();
let leg = self.list_leg(kind);
quote! {
#binding_gate! {
#database_gate! {
const _: () = {
#prelude
#names
#[#ag::Object(crate = #shelf, name = #sdl)]
impl #name {
#leg
}
};
}
}
}
}
pub(crate) fn queries(&self) -> proc_macro2::TokenStream {
let declaration = self.queries_type();
let binding = self.wire_binding();
let face = self.queries_face();
quote! {
#declaration
#binding
#face
}
}
}