use quote::{format_ident, quote};
use crate::{
method::wire_method,
model::{DatabaseBackend, Graphql, RecordModel, default_queries_name},
};
#[cfg(test)]
mod batch_lane_tests;
#[cfg(test)]
mod page_name_tests;
#[cfg(test)]
mod page_tower_tests;
#[cfg(test)]
mod tests;
struct LineageStep {
field: String,
parameter: syn::Ident,
with: syn::Ident,
filter: proc_macro2::TokenStream,
wire: syn::Type,
}
use crate::emit::{lower_initial as root_field, raise_initial as page_type};
impl RecordModel {
pub(crate) fn wire_query_row(&self) -> Option<&DatabaseBackend> {
self.graphql.as_ref()?;
let raises = self.wire_rows();
self
.queryable()
.into_iter()
.find(|database| raises.iter().any(|row| row.kind() == database.kind()))
}
pub(crate) fn wire_filters(&self) -> bool {
self.wire_query_row().is_some() && self.orderable() && !self.ordered_columns().is_empty()
}
pub fn degenerate_plural(&self) -> Option<String> {
let graphql = self.graphql.as_ref()?;
if graphql.plural.is_some() || !self.wire_filters() {
return None;
}
let single = root_field(&super::wire::published_output(graphql, self));
let page = root_field(&super::wire::published_plural(graphql, self));
(page == single).then_some(single)
}
pub(super) fn queries_type(&self) -> proc_macro2::TokenStream {
if self.graphql.is_none() || self.wire_query_row().is_none() {
return proc_macro2::TokenStream::new();
}
let vis = &self.vis;
let record = &self.record;
let name = default_queries_name(record);
let doc = super::leading(&format!(
"The root fields a [`{record}`] answers — one row by its id, and a page of them.\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."
));
quote! {
#[doc = #doc]
#[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::marker::Copy, ::core::default::Default)]
#vis struct #name;
}
}
pub(super) fn queries_face(&self) -> proc_macro2::TokenStream {
let Some(graphql) = self.graphql.as_ref() else {
return proc_macro2::TokenStream::new();
};
let Some(database) = self.wire_query_row() else {
return proc_macro2::TokenStream::new();
};
let name = default_queries_name(&self.record);
let ag = self.framework(&[], "async_graphql");
let shelf = self.vendored("async_graphql");
let single = self.single_leg(graphql, database);
let list = self.list_leg(graphql, database);
let lineage = self.lineage_leg(graphql, database);
let names = self.page_names(graphql, !list.is_empty() || !lineage.is_empty());
let sdl = name.to_string();
let gate = self.framework(&["gate"], &database.kind().gate().to_string());
let prelude = super::wire::prelude();
quote! {
#gate! {
const _: () = {
#prelude
#names
#[#ag::Object(crate = #shelf, name = #sdl)]
impl #name {
#single
#list
#lineage
}
};
}
}
}
fn page_names(&self, graphql: &Graphql, paged: bool) -> proc_macro2::TokenStream {
if !paged {
return proc_macro2::TokenStream::new();
}
let ag = self.framework(&[], "async_graphql");
let base = page_type(&super::wire::published_plural(graphql, self));
let marker = |declared: Option<&String>, word_suffix: &str, hook: &str, what: &str| {
let word = declared.map_or_else(|| format!("{base}{word_suffix}"), ToOwned::to_owned);
let name = format_ident!("{}{word_suffix}Name", self.record);
let hook = self.framework(&["graphql"], hook);
let doc = super::leading(&if declared.is_some() {
format!(
"What the schema calls {what} of [`{record}`]s — `{word}`, the word the declaration \
wrote.\n\nThis is the naming tower's TOP: it covers the plural-built word outright, so a \
`plural = \"…\"` beside it moves the other names and not this one. It also exits the \
Relay Cursor Connections spelling, and with it the automatic recognition Relay, Apollo \
and schema codegen give a page: those tools find a connection by the \
`<Node>Connection`/`<Node>Edge` shape rather than by its fields. That is the trade the \
knob exists to make, and it is made per record.",
record = self.record
)
} else {
format!(
"What the schema calls {what} of [`{record}`]s — `{word}`, built from this record's \
PLURAL, which is the one word its list field is named from as well.\n\nThe Relay Cursor \
Connections specification spells this over the NODE's name; this framework spells it over \
the plural, so one declaration's page reads as one phrase and a `plural = \"…\"` \
correcting the English moves the field and both type names at once. Tooling that finds a \
page by the node's stem rather than by its fields sees a name it does not recognise: that \
is the trade, made once for every record. `connection(rename = \"…\")` and \
`edge(rename = \"…\")` are the tier above this one.",
record = self.record
)
});
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(
graphql.connection.as_ref(),
"Connection",
"ConnectionNameType",
"a page",
);
let edge = marker(graphql.edge.as_ref(), "Edge", "EdgeNameType", "one edge");
quote!(#connection #edge)
}
fn page_name_arguments(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
let connection = format_ident!("{}ConnectionName", self.record);
let edge = format_ident!("{}EdgeName", self.record);
(quote!(#connection), quote!(#edge))
}
fn single_leg(&self, graphql: &Graphql, database: &DatabaseBackend) -> proc_macro2::TokenStream {
let ag = self.framework(&[], "async_graphql");
let door = self.framework(&["graphql"], "SqlDoor");
let batch = self.framework(&["graphql"], "BatchDoor");
let refused = self.framework(&["graphql"], "refused");
let rows = self.framework(&["query", "sql"], "rows");
let crossing = self.framework(&["graphql"], "ToGraphqlInput");
let refused_address = self.framework(&["graphql"], "refused_address");
let output = graphql.output.safe();
let row = database.name();
let backend = database.backend_type(self);
let id_ty = &self.key.id.ty;
let field = root_field(&super::wire::published_output(graphql, self));
let method = wire_method(&format_ident!("{}", self.snake()));
let ctx = wire_method(&format_ident!("ctx"));
let id = wire_method(&format_ident!("id"));
let raise = self.wire_crossing(graphql, database);
quote! {
#[graphql(name = #field)]
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#[graphql(name = "id")] #id: <#id_ty as #crossing>::Input,
) -> #ag::Result<::core::option::Option<#output>> {
let __ingraph_hit = match #ag::Context::data_opt::<#batch<#id_ty, #row>>(#ctx) {
::core::option::Option::Some(__ingraph_batch) => {
let __ingraph_id = <#id_ty as #crossing>::cross(#id)
.map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
#batch::one(__ingraph_batch, __ingraph_id)
.await
.map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?
}
::core::option::Option::None => {
let __ingraph_door = #ag::Context::data::<#door<#backend>>(#ctx)?;
let __ingraph_id = <#id_ty as #crossing>::cross(#id)
.map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
let __ingraph_rows = #rows::<#row, #backend, _>(
#door::pool(__ingraph_door),
::core::slice::from_ref(&__ingraph_id),
)
.await
.map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
::core::iter::Iterator::next(
&mut ::core::iter::IntoIterator::into_iter(__ingraph_rows),
)
}
};
match __ingraph_hit {
::core::option::Option::Some(__ingraph_row) => ::core::result::Result::Ok(
::core::option::Option::Some(#raise?),
),
::core::option::Option::None => {
::core::result::Result::Ok(::core::option::Option::None)
}
}
}
}
}
fn list_leg(&self, graphql: &Graphql, database: &DatabaseBackend) -> proc_macro2::TokenStream {
if !self.orderable() || self.ordered_columns().is_empty() {
return proc_macro2::TokenStream::new();
}
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 output = graphql.output.safe();
let order_by = self.order_by.safe();
let cursor = database.cursor_name();
let backend = database.backend_type(self);
let field = root_field(&super::wire::published_plural(graphql, self));
let method = wire_method(&format_ident!("{}_list", self.snake()));
let ctx = wire_method(&format_ident!("ctx"));
let (order, first, last, after, before) = (
wire_method(&format_ident!("order_by")),
wire_method(&format_ident!("first")),
wire_method(&format_ident!("last")),
wire_method(&format_ident!("after")),
wire_method(&format_ident!("before")),
);
let filter = graphql.filter.safe();
let comparison = database.comparison_name();
let try_from_filter = self.framework(&["comparison"], "TryFromFilter");
let refused_filter = self.framework(&["graphql"], "refused_filter");
let predicate = wire_method(&format_ident!("where"));
let arity = super::wide_signature();
let walk = self.page_walk(graphql, database);
let (connection_name, edge_name) = self.page_name_arguments();
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_scope: ::core::option::Option<#comparison<#backend>> =
::core::option::Option::None;
#walk
}
}
}
fn page_walk(&self, graphql: &Graphql, database: &DatabaseBackend) -> proc_macro2::TokenStream {
let refused = self.framework(&["graphql"], "refused");
let orderings = self.framework(&["graphql"], "Orderings");
let page_request = self.framework(&["graphql"], "PageRequest");
let door = self.framework(&["graphql"], "SqlDoor");
let order_by = self.order_by.safe();
let cursor = database.cursor_name();
let record = &self.record;
let finder = database.kind().finder();
let crossing = self.wire_crossing(graphql, database);
let (order, first, last, after, before) = (
wire_method(&format_ident!("order_by")),
wire_method(&format_ident!("first")),
wire_method(&format_ident!("last")),
wire_method(&format_ident!("after")),
wire_method(&format_ident!("before")),
);
quote! {
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 = #record::#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 = match &__ingraph_scope {
::core::option::Option::Some(__ingraph_scoping) => __ingraph_found.scope(__ingraph_scoping),
::core::option::Option::None => __ingraph_found,
};
let __ingraph_found = __ingraph_found.order(&__ingraph_terms);
let __ingraph_page = 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).rows().await
}
::core::option::Option::None => __ingraph_walk.rows().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).rows().await
}
::core::option::Option::None => __ingraph_walk.rows().await,
}
}
}
.map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
__ingraph_page.into_connection(|__ingraph_row| #crossing)
}
}
fn lineage_leg(&self, graphql: &Graphql, database: &DatabaseBackend) -> proc_macro2::TokenStream {
let steps = self.lineage_steps(graphql);
if steps.is_empty() || !self.orderable() || self.ordered_columns().is_empty() {
return proc_macro2::TokenStream::new();
}
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 equals = self.framework(&["graphql"], "EqualsFilter");
let crossing = self.framework(&["graphql"], "ToGraphqlInput");
let refused_address = self.framework(&["graphql"], "refused_address");
let refused_filter = self.framework(&["graphql"], "refused_filter");
let try_from_filter = self.framework(&["comparison"], "TryFromFilter");
let output = graphql.output.safe();
let order_by = self.order_by.safe();
let filter = graphql.filter.safe();
let comparison = database.comparison_name();
let cursor = database.cursor_name();
let backend = database.backend_type(self);
let field = format!(
"{}Lineage",
root_field(&super::wire::published_output(graphql, self))
);
let method = wire_method(&format_ident!("{}_lineage", self.snake()));
let ctx = wire_method(&format_ident!("ctx"));
let (order, first, last, after, before) = (
wire_method(&format_ident!("order_by")),
wire_method(&format_ident!("first")),
wire_method(&format_ident!("last")),
wire_method(&format_ident!("after")),
wire_method(&format_ident!("before")),
);
let parameters = steps.iter().map(|step| {
let (name, ident, wire) = (&step.field, &step.parameter, &step.wire);
quote!(#[graphql(name = #name)] #ident: <#wire as #crossing>::Input,)
});
let ancestry = steps.iter().map(|step| {
let (ident, wire, with, guard) = (&step.parameter, &step.wire, &step.with, &step.filter);
quote! {
.#with(<#guard as #equals<#wire>>::equals(
<#wire as #crossing>::cross(#ident)
.map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?,
))
}
});
let predicate = wire_method(&format_ident!("where"));
let arity = super::wide_signature();
let walk = self.page_walk(graphql, database);
let (connection_name, edge_name) = self.page_name_arguments();
quote! {
#[graphql(name = #field)]
#arity
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#(#parameters)*
#[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_ancestry = <#filter as ::core::default::Default>::default() #(#ancestry)*;
let __ingraph_scope = ::core::option::Option::Some(
<#comparison<#backend> as #try_from_filter<#filter>>::try_from_filter(__ingraph_ancestry)
.map_err(|__ingraph_refusal| #refused_filter(&__ingraph_refusal))?,
);
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,
};
#walk
}
}
}
fn lineage_steps(&self, graphql: &Graphql) -> Vec<LineageStep> {
let Some(lineage) = self.lineage.as_ref() else {
return Vec::new();
};
let path = lineage.path();
if path.is_empty() {
return Vec::new();
}
let rows = graphql.filter_rows(self);
let steps: Vec<LineageStep> = path
.iter()
.filter_map(|step| {
let row = rows.iter().find(|row| row.member == step.source)?;
Some(LineageStep {
field: super::wire::wire_field(&row.declared, &row.member),
parameter: wire_method(&row.member),
with: crate::method::Member::With.name(&row.member),
wire: row.wire.clone(),
filter: row.filter.clone(),
})
})
.collect();
if steps.len() == path.len() {
steps
} else {
Vec::new()
}
}
fn wire_crossing(
&self,
graphql: &Graphql,
database: &DatabaseBackend,
) -> proc_macro2::TokenStream {
let output = graphql.output.safe();
let row = database.name();
let refused_row = self.framework(&["graphql"], "refused_row");
quote! {
<#output as ::core::convert::TryFrom<#row>>::try_from(__ingraph_row)
.map_err(|__ingraph_refusal| #refused_row(&__ingraph_refusal))
}
}
fn snake(&self) -> String {
use heck::ToSnakeCase as _;
self.record.to_string().to_snake_case()
}
}