use quote::ToTokens;
use crate::{
construct::{Build, Construction},
model::{
Column, Condition, Derived, FallibleConversion, FanIn, Field, Fusion, Key, Kind, Lineage,
Mirror, NodeKind, Product, Products, Projection, RecordModel, Reference, Shape, Subscription,
Through, Upstream, Upstreams, default_downstream_name, default_in_name, default_key_name,
default_lineage_name, default_out_kind_name, default_out_name, fanned_lineage,
fanned_lineage_column, one_storage_marker,
},
prefix::EmissionPrefix,
};
fn video_track() -> RecordModel {
let mut model = model("VideoTrack", &["media_id", "video_id"], "id");
model.key.name = ident("TrackAddress");
model.key.path[0].project = Projection::Copied;
let lineage = model.lineage.as_mut().expect("a grandchild has a path");
lineage.name = ident("TrackScope");
lineage.path_mut()[0].project = Projection::Copied;
mark(&mut model, "media_id");
model
}
fn mark(model: &mut RecordModel, name: &str) {
model
.fields
.iter_mut()
.find(|field| field.column.name == name)
.expect("a field of the record")
.column
.project = Projection::Copied;
}
fn label(model: &mut RecordModel, source: &str, marker: Marker) {
let source = ident(source);
model
.fields
.iter_mut()
.find(|field| field.column.source == source)
.expect("a field of the record")
.marker = Some(marker);
}
fn video() -> RecordModel {
model("Video", &["media_id"], "id")
}
fn media() -> RecordModel {
let mut model = model("Media", &[], "id");
model.key.id.project = Projection::Copied;
mark(&mut model, "id");
model
}
fn fused() -> RecordModel {
let mut model = video();
model.upstreams = Some(Upstreams::Fused(Fusion {
parent: syn::parse_quote!(media::Frame),
others: vec![syn::parse_quote!(asr::Segment)],
mirrors: vec![Mirror {
column: ident("media_id"),
from: ident("frame"),
}],
}));
model
}
fn fanned() -> RecordModel {
fanned_under(EmissionPrefix::default())
}
fn fanned_under(prefix: EmissionPrefix) -> RecordModel {
let mut model = video();
model.prefix = prefix;
let kinds = vec![
Kind {
node: syn::parse_quote!(media::Frame),
variant: ident("Frame"),
},
Kind {
node: syn::parse_quote!(asr::Segment),
variant: ident("Segment"),
},
];
model.upstreams = Some(Upstreams::Fanned(FanIn {
kinds: kinds.clone(),
}));
let lineage = model.lineage.as_mut().expect("a child has a lineage");
lineage.shape = Shape::Kinds(kinds);
let column = &mut model.key.path[0];
column.name = fanned_lineage_column();
column.source = fanned_lineage(&model.prefix);
column.ty = syn::parse_quote!(VideoLineage);
model
}
pub(crate) fn model(record: &str, lineage: &[&str], id: &str) -> RecordModel {
let record = ident(record);
let identity: Vec<Column> = lineage
.iter()
.map(|name| column(name))
.chain([column(id)])
.collect();
let mut chapters = column_of("chapters", generic("Vec", "Uuid7"));
chapters.project = Projection::Repeated;
let mut cover = column_of("cover_id", generic("Option", "Uuid7"));
cover.project = Projection::Optional;
let data = [column_of("checksum", ty("u64")), chapters, cover];
RecordModel {
prefix: EmissionPrefix::default(),
kind: NodeKind::Record,
options: None,
receipt: None,
remote: None,
construction: Construction::default(),
key: Key {
name: default_key_name(&record),
path: lineage.iter().map(|name| column(name)).collect(),
id: column(id),
},
krate: ingraph_path(),
vis: syn::Visibility::Public(syn::token::Pub::default()),
fields: identity
.into_iter()
.map(|column| Field {
column,
identity: true,
marker: None,
sortable: false,
indexed: false,
reference: None,
skip: None,
docs: Vec::new(),
condition: Condition::always(),
build: Build::default(),
})
.chain(data.into_iter().map(|column| Field {
column,
identity: false,
marker: None,
sortable: false,
indexed: false,
reference: None,
skip: None,
docs: Vec::new(),
condition: Condition::always(),
build: Build::default(),
}))
.collect(),
lineage: (!lineage.is_empty()).then(|| Lineage {
name: default_lineage_name(&record),
shape: Shape::Path(lineage.iter().map(|name| column(name)).collect()),
}),
persist: None,
errors: Vec::new(),
order_by: RustSafeName::from_ident(&default_order_by_name(&record)),
progress: None,
graphql: None,
derived: Vec::new(),
artifacts: Vec::new(),
implements: Vec::new(),
subscribe: None,
teardown: false,
asynchronous: None,
streaming: None,
autonomous: None,
attributed: false,
upstreams: None,
subscriptions: None,
products: None,
polls: None,
tracing: None,
record,
}
}
fn generic(outer: &str, item: &str) -> syn::Type {
let mut segment = syn::PathSegment::from(ident(outer));
let mut args = syn::punctuated::Punctuated::new();
args.push(syn::GenericArgument::Type(ty(item)));
segment.arguments = syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
colon2_token: None,
lt_token: syn::token::Lt::default(),
args,
gt_token: syn::token::Gt::default(),
});
syn::Type::Path(syn::TypePath {
attrs: Vec::new(),
qself: None,
path: syn::Path {
leading_colon: None,
segments: core::iter::once(segment).collect(),
},
})
}
fn column_of(name: &str, ty: syn::Type) -> Column {
Column {
name: ident(name),
source: ident(name),
ty,
project: Projection::Borrowed,
}
}
fn column(name: &str) -> Column {
column_of(name, ty("Uuid7"))
}
fn private(mut model: RecordModel) -> RecordModel {
model.vis = syn::Visibility::Inherited;
model
}
fn ident(name: &str) -> syn::Ident {
syn::Ident::new(name, proc_macro2::Span::call_site())
}
fn ty(name: &str) -> syn::Type {
syn::Type::Path(syn::TypePath {
attrs: Vec::new(),
qself: None,
path: ident(name).into(),
})
}
fn ingraph_path() -> syn::Path {
syn::Path {
leading_colon: Some(syn::token::PathSep::default()),
segments: core::iter::once(syn::PathSegment::from(ident("ingraph"))).collect(),
}
}
pub(crate) fn emission(model: &RecordModel) -> syn::File {
let file: syn::File = syn::parse2(model.emit()).expect("the emission is a parsable file");
syn::File {
items: ungate(file.items),
..file
}
}
fn is_gate(path: &syn::Path) -> bool {
path
.segments
.iter()
.skip_while(|segment| segment.ident != "__private")
.nth(1)
.is_some_and(|segment| segment.ident == "gate")
}
fn is_complement(path: &syn::Path) -> bool {
path
.segments
.last()
.is_some_and(|segment| segment.ident.to_string().starts_with("if_no_"))
}
pub(crate) fn ungate(items: Vec<syn::Item>) -> Vec<syn::Item> {
let mut opened = Vec::with_capacity(items.len());
for item in items {
match item {
syn::Item::Macro(gate) if is_gate(&gate.mac.path) && is_complement(&gate.mac.path) => {}
syn::Item::Macro(gate) if is_gate(&gate.mac.path) => {
let held: syn::File = syn::parse2(gate.mac.tokens).expect("a gate holds parsable items");
opened.extend(ungate(held.items));
}
syn::Item::Const(mut anonymous) => {
if let syn::Expr::Block(block) = &mut *anonymous.expr {
let statements = core::mem::take(&mut block.block.stmts);
block.block.stmts = ungate_statements(statements);
}
opened.push(syn::Item::Const(anonymous));
}
other => opened.push(other),
}
}
opened
}
fn ungate_statements(statements: Vec<syn::Stmt>) -> Vec<syn::Stmt> {
let mut opened = Vec::with_capacity(statements.len());
for statement in statements {
match statement {
syn::Stmt::Macro(gate) if is_gate(&gate.mac.path) && is_complement(&gate.mac.path) => {}
syn::Stmt::Macro(gate) if is_gate(&gate.mac.path) => {
let held: syn::File = syn::parse2(gate.mac.tokens).expect("a gate holds parsable items");
opened.extend(ungate(held.items).into_iter().map(syn::Stmt::Item));
}
syn::Stmt::Item(item) => opened.extend(ungate(vec![item]).into_iter().map(syn::Stmt::Item)),
other => opened.push(other),
}
}
opened
}
fn gated(model: &RecordModel) -> Vec<(String, Vec<String>)> {
fn walk(items: &[syn::Item], into: &mut Vec<(String, Vec<String>)>) {
for item in items {
match item {
syn::Item::Macro(gate) if is_gate(&gate.mac.path) => {
let held: syn::File =
syn::parse2(gate.mac.tokens.clone()).expect("a gate holds parsable items");
let leaf = gate
.mac
.path
.segments
.last()
.expect("a path has a last segment")
.ident
.to_string();
let traits = held
.items
.iter()
.filter_map(|item| match item {
syn::Item::Impl(item) => item
.trait_
.as_ref()
.map(|(path, _)| format!("{} for {}", tight(path), impl_of(item))),
_ => None,
})
.collect();
into.push((leaf, traits));
}
syn::Item::Const(anonymous) => {
if let syn::Expr::Block(block) = &*anonymous.expr {
for statement in &block.block.stmts {
match statement {
syn::Stmt::Macro(gate) if is_gate(&gate.mac.path) => walk(
&[syn::Item::Macro(syn::ItemMacro {
attrs: gate.attrs.clone(),
ident: None,
mac: gate.mac.clone(),
semi_token: gate.semi_token,
})],
into,
),
syn::Stmt::Item(item) => walk(core::slice::from_ref(item), into),
_ => {}
}
}
}
}
_ => {}
}
}
}
let file: syn::File = syn::parse2(model.emit()).expect("the emission is a parsable file");
let mut found = Vec::new();
walk(&file.items, &mut found);
found
}
fn structs(file: &syn::File) -> Vec<&syn::ItemStruct> {
file
.items
.iter()
.filter_map(|item| match item {
syn::Item::Struct(item) => Some(item),
_ => None,
})
.collect()
}
fn names(file: &syn::File) -> Vec<String> {
structs(file).iter().map(|s| s.ident.to_string()).collect()
}
fn declared_types(file: &syn::File) -> Vec<String> {
all_items(file)
.into_iter()
.filter_map(|item| match item {
syn::Item::Struct(item) => Some(item.ident.to_string()),
syn::Item::Enum(item) => Some(item.ident.to_string()),
_ => None,
})
.collect()
}
fn scoped_types(file: &syn::File) -> Vec<String> {
file
.items
.iter()
.filter_map(|item| match item {
syn::Item::Struct(item) => Some(item.ident.to_string()),
syn::Item::Enum(item) => Some(item.ident.to_string()),
_ => None,
})
.collect()
}
fn fields(item: &syn::ItemStruct) -> Vec<String> {
named(item)
.iter()
.map(|f| f.ident.as_ref().expect("named").to_string())
.collect()
}
fn named(item: &syn::ItemStruct) -> &syn::punctuated::Punctuated<syn::Field, syn::Token![,]> {
match &item.fields {
syn::Fields::Named(named) => &named.named,
syn::Fields::Unnamed(_) | syn::Fields::Unit => panic!("an emitted type has named fields"),
}
}
fn documented(attrs: &[syn::Attribute]) -> bool {
attrs.iter().any(|attr| attr.path().is_ident("doc"))
}
fn all_items(file: &syn::File) -> Vec<&syn::Item> {
fn walk<'a>(item: &'a syn::Item, into: &mut Vec<&'a syn::Item>) {
into.push(item);
if let syn::Item::Const(anonymous) = item
&& let syn::Expr::Block(block) = &*anonymous.expr
{
for statement in &block.block.stmts {
if let syn::Stmt::Item(inner) = statement {
walk(inner, into);
}
}
}
}
let mut items = Vec::new();
for item in &file.items {
walk(item, &mut items);
}
items
}
fn impls(file: &syn::File) -> Vec<&syn::ItemImpl> {
all_items(file)
.into_iter()
.filter_map(|item| match item {
syn::Item::Impl(item) => Some(item),
_ => None,
})
.collect()
}
fn inherent(file: &syn::File) -> Vec<&syn::ItemImpl> {
impls(file)
.into_iter()
.filter(|item| item.trait_.is_none())
.collect()
}
fn trait_impls(file: &syn::File) -> Vec<(&syn::ItemImpl, &syn::Path)> {
impls(file)
.into_iter()
.filter_map(|item| item.trait_.as_ref().map(|(path, _)| (item, path)))
.collect()
}
fn framework_rooted(path: &syn::Path, krate: &syn::Path) -> bool {
const VENDORED: &[&str] = &["async_graphql", "serde", "sqlx"];
let segments: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
let root: Vec<String> = krate.segments.iter().map(|s| s.ident.to_string()).collect();
let rooted =
segments.first().is_some_and(|first| first == "crate") || segments.starts_with(&root);
let vendored = segments
.iter()
.skip_while(|segment| *segment != "__private")
.nth(1)
.is_some_and(|segment| VENDORED.contains(&segment.as_str()));
rooted && !vendored
}
fn unauthorised_framework_impls(model: &RecordModel, file: &syn::File) -> Vec<String> {
trait_impls(file)
.into_iter()
.filter(|(_, path)| framework_rooted(path, &model.krate))
.filter(|(item, path)| !authorised(model, item, path))
.map(|(item, path)| format!("{} for {}", tight(path), impl_of(item)))
.collect()
}
fn authorised(model: &RecordModel, item: &syn::ItemImpl, path: &syn::Path) -> bool {
let shelved: Vec<String> = path
.segments
.iter()
.skip_while(|segment| segment.ident != "__private")
.skip(1)
.map(|segment| segment.ident.to_string())
.collect();
let filter = model
.graphql
.as_ref()
.map(|graphql| graphql.filter.safe().to_string());
let databases = || model.persist.iter().flat_map(|persist| &persist.backends);
let rows: Vec<String> = databases()
.map(|database| database.name().to_string())
.collect();
let comparisons: Vec<String> = databases()
.map(|database| format!("{}<{}>", database.comparison_name(), database_parameter()))
.collect();
let backends: Vec<String> = databases()
.map(|database| tight(database.backend_type(model)))
.collect();
let map = shelved == ["comparison", "ToDatabaseComparison"]
&& filter.is_some_and(|filter| impl_of(item) == filter)
&& storage_argument(path).is_some_and(|storage| rows.contains(&storage));
let lowering =
shelved == ["comparison", "ComplexComparison"] && comparisons.contains(&impl_of(item));
let binding = shelved == ["transform", "Transformer"] && model.record == impl_of(item);
let wire = shelved == ["transform", "Graphql"] && model.record == impl_of(item);
let half = |member: &str, name: Option<&RustSafeName>| {
shelved == ["transform", member] && name.is_some_and(|name| *name.safe() == impl_of(item))
};
let wire_input = half("GraphqlInput", model.graphql.as_ref().map(|g| &g.input));
let wire_output = half("GraphqlOutput", model.graphql.as_ref().map(|g| &g.output));
let identity = shelved == ["transform", "Identifiable"]
&& (model.record == impl_of(item) || model.key.name == impl_of(item));
let address = shelved == ["store", "KeySegments"] && model.key.name == impl_of(item);
let sent_address = shelved == ["graphql", "ToGraphqlInput"] && model.key.name == impl_of(item);
let vocabulary = shelved == ["transform", "Record"]
&& model.record == impl_of(item)
&& storage_argument(path).is_some_and(|backend| backends.contains(&backend));
let referred = || {
model
.fields
.iter()
.filter_map(|field| field.reference.as_ref())
};
let pairing = shelved == ["transform", "Related"]
&& model.record == impl_of(item)
&& storage_argument(path)
.is_some_and(|target| referred().any(|reference| tight(&reference.target) == target));
let membership = shelved == ["transform", "Implements"]
&& model.record == impl_of(item)
&& storage_argument(path).is_some_and(|interface| {
model
.implements
.iter()
.any(|declared| tight(declared) == interface)
});
let artifact = shelved == ["transform", "Reference"]
&& model
.fields
.iter()
.filter(|field| field.reference.is_some())
.any(|field| model.artifact(&field.column.source) == impl_of(item));
let subject = shelved == ["graphql", "ToSubjectPath"] && *model.order_by.safe() == impl_of(item);
let emits = shelved.first().is_some_and(|module| module == "operator")
&& shelved.get(1).is_some_and(|name| name == "Emits")
&& model.record == impl_of(item);
let sole = shelved == ["operator", "SoleProduct"] && model.record == impl_of(item);
let products =
shelved == ["operator", "Products"] && default_out_name(&model.record) == impl_of(item);
let vocabulary_of_products =
shelved == ["operator", "ProductKind"] && default_out_kind_name(&model.record) == impl_of(item);
let routing = shelved == ["drive", "Sink"]
&& default_downstream_name(&model.record) == impl_of(item)
&& storage_argument(path).is_some_and(|out| default_out_name(&model.record) == out);
let facts = shelved == ["drive", "Declared"] && model.record == impl_of(item);
let blueprint = shelved == ["schema", "Describe"]
&& model.record == impl_of(item)
&& storage_argument(path).is_some_and(|backend| backends.contains(&backend));
let projection = crate::emit::framework(&model.krate, &["drive"], "RootProjection");
let record = &model.record;
let attribution = shelved == ["drive", "Attributes"]
&& storage_argument(path).is_some_and(|root| model.record == root)
&& impl_of(item) == tight(quote::quote!(#projection<#record>));
map
|| blueprint
|| lowering
|| binding
|| wire
|| wire_input
|| wire_output
|| identity
|| address
|| sent_address
|| vocabulary
|| pairing
|| artifact
|| membership
|| subject
|| emits
|| sole
|| products
|| vocabulary_of_products
|| routing
|| facts
|| attribution
}
fn database_parameter() -> String {
crate::emit::parameter("DB").to_string()
}
fn storage_argument(path: &syn::Path) -> Option<String> {
let syn::PathArguments::AngleBracketed(arguments) = &path.segments.last()?.arguments else {
return None;
};
arguments.args.iter().find_map(|argument| match argument {
syn::GenericArgument::Type(ty) => Some(tight(ty)),
_ => None,
})
}
fn methods(item: &syn::ItemImpl) -> Vec<&syn::ImplItemFn> {
item
.items
.iter()
.filter_map(|item| match item {
syn::ImplItem::Fn(item) => Some(item),
_ => None,
})
.collect()
}
fn method_names(file: &syn::File) -> Vec<String> {
inherent(file)
.iter()
.flat_map(|item| methods(item))
.map(|method| method.sig.ident.to_string())
.collect()
}
fn key_methods(file: &syn::File) -> Vec<&syn::ImplItemFn> {
methods(inherent(file)[0])
}
fn impl_of(item: &syn::ItemImpl) -> String {
tight(&item.self_ty)
}
fn owner_of(item: &syn::ItemImpl) -> String {
match &*item.self_ty {
syn::Type::Path(path) => path
.path
.segments
.last()
.expect("a path has a last segment")
.ident
.to_string(),
other => panic!("an inherent impl is for a named type: {}", tight(other)),
}
}
fn methods_of(file: &syn::File, name: &str) -> Vec<String> {
inherent(file)
.into_iter()
.filter(|item| impl_of(item) == name)
.flat_map(methods)
.map(|method| method.sig.ident.to_string())
.collect()
}
fn method_of<'a>(file: &'a syn::File, type_name: &str, name: &str) -> &'a syn::ImplItemFn {
inherent(file)
.into_iter()
.filter(|item| impl_of(item) == type_name)
.flat_map(methods)
.find(|method| method.sig.ident == name)
.unwrap_or_else(|| panic!("`{type_name}::{name}` is emitted"))
}
fn returns(method: &syn::ImplItemFn) -> String {
match &method.sig.output {
syn::ReturnType::Type(_, ty) => tight(ty),
syn::ReturnType::Default => "()".to_owned(),
}
}
fn key_method<'a>(file: &'a syn::File, name: &str) -> &'a syn::ImplItemFn {
key_methods(file)
.into_iter()
.find(|method| method.sig.ident == name)
.unwrap_or_else(|| panic!("`{name}` is emitted"))
}
fn is_const(method: &syn::ImplItemFn) -> bool {
method.sig.constness.is_some()
}
fn returns_reference(method: &syn::ImplItemFn) -> bool {
matches!(&method.sig.output, syn::ReturnType::Type(_, ty) if matches!(**ty, syn::Type::Reference(_)))
}
fn must_use(method: &syn::ImplItemFn) -> bool {
method
.attrs
.iter()
.any(|attr| attr.path().is_ident("must_use"))
}
fn tight(tokens: impl ToTokens) -> String {
tokens.to_token_stream().to_string().replace(' ', "")
}
fn docs(attrs: &[syn::Attribute]) -> String {
attrs
.iter()
.filter(|attr| attr.path().is_ident("doc"))
.map(|attr| tight(&attr.meta))
.collect()
}
#[test]
fn a_grandchild_emits_a_key_and_a_lineage() {
assert_eq!(
names(&emission(&video_track())),
["TrackAddress", "TrackScope"],
"the fixture renames both, so this doubles as the proof that a rename reaches emission"
);
}
#[test]
fn the_emitter_uses_the_models_names_not_the_convention() {
let conventional = model("VideoTrack", &["media_id", "video_id"], "id");
assert_eq!(
names(&emission(&conventional)),
["VideoTrackKey", "VideoTrackLineage"]
);
assert_eq!(
names(&emission(&video_track())),
["TrackAddress", "TrackScope"]
);
}
#[test]
fn the_key_lays_out_lineage_root_first_then_the_id() {
let file = emission(&video_track());
assert_eq!(
fields(structs(&file)[0]),
["media_id", "video_id", "id"],
"flat, and in exactly that order — root attribution reads the leading column and prefix \
deletes range-scan it"
);
assert_eq!(
fields(structs(&file)[1]),
["media_id", "video_id"],
"the lineage type is the path without the id"
);
}
#[test]
fn a_root_emits_a_key_and_no_lineage_type_at_all() {
let file = emission(&media());
assert_eq!(names(&file), ["MediaKey"], "absence by omission");
assert_eq!(fields(structs(&file)[0]), ["id"]);
}
#[test]
fn a_child_carries_its_one_parent() {
let file = emission(&video());
assert_eq!(names(&file), ["VideoKey", "VideoLineage"]);
assert_eq!(fields(structs(&file)[0]), ["media_id", "id"]);
assert_eq!(fields(structs(&file)[1]), ["media_id"]);
}
#[test]
fn a_storage_node_mints_the_one_storage_marker_at_module_scope() {
let file = emission(&media());
let minted: Vec<String> = file
.items
.iter()
.filter_map(|item| match item {
syn::Item::Const(named) => Some(named.ident.to_string()),
_ => None,
})
.filter(|name| name != "_")
.collect();
assert_eq!(
minted,
[one_storage_marker(&EmissionPrefix::default(), &ident("Media")).to_string()],
"one marker, named by the authority both derives read"
);
}
#[test]
fn a_platform_mark_moves_every_name_the_record_mints() {
let mut model = media();
model.prefix = EmissionPrefix::new("__mg");
let rendered = prettyplease::unparse(&emission(&model));
assert!(
rendered.contains(&one_storage_marker(&model.prefix, &ident("Media")).to_string()),
"the storage marker is minted under the model's own mark",
);
assert!(
!rendered.contains("__ig_Media_holds_one_storage"),
"and `ingraph`'s spelling of it is nowhere in the expansion",
);
}
#[test]
fn a_platform_mark_moves_the_injected_lineage_field() {
let rendered = prettyplease::unparse(&emission(&fanned_under(EmissionPrefix::new("__mg"))));
assert!(
rendered.contains("__mg_lineage__"),
"the injected field wears the platform's mark"
);
assert!(
!rendered.contains("__ig_lineage__"),
"and nothing in the expansion still spells `ingraph`'s",
);
}
#[test]
fn two_frameworks_declarations_stand_beside_each_other() {
let ingraph = prettyplease::unparse(&emission(&fanned()));
let mut platform = media();
platform.prefix = EmissionPrefix::new("__mg");
let platform = prettyplease::unparse(&emission(&platform));
assert!(ingraph.contains("__ig_lineage__"), "{ingraph}");
assert!(!ingraph.contains("__mg_lineage__"), "{ingraph}");
assert!(
platform.contains("__mg_Media_holds_one_storage"),
"{platform}"
);
assert!(
!platform.contains("__ig_Media_holds_one_storage"),
"{platform}"
);
}
#[test]
fn a_model_that_names_no_mark_expands_exactly_as_before() {
assert!(
prettyplease::unparse(&emission(&fanned())).contains("__ig_lineage__"),
"the injected lineage field is where it always was",
);
assert!(
prettyplease::unparse(&emission(&media())).contains("__ig_Media_holds_one_storage"),
"and so is the storage marker",
);
}
#[test]
fn a_subscriber_emits_its_upstream_under_a_node_bound() {
let mut model = media();
model.subscribe = Some(syn::parse_quote!(asr::TranscriptSegment));
let rendered = prettyplease::unparse(&emission(&model));
assert!(
rendered.contains(
"fn __ig_subscribes_to<\n __INGRAPH_UPSTREAM__: ::ingraph::__private::transform::Transformer,\n >()"
),
"the bound says what a subscribe target has to BE: {rendered}"
);
assert!(
rendered.contains("__ig_subscribes_to::<asr::TranscriptSegment>"),
"and the path is handed over exactly as written: {rendered}"
);
}
#[test]
fn a_node_that_subscribes_to_nothing_emits_no_audit() {
assert!(
!prettyplease::unparse(&emission(&media())).contains("__ig_subscribes_to"),
"no upstream, no audit"
);
}
#[test]
fn a_node_that_opted_into_the_goodbye_emits_it_under_a_teardown_bound() {
let mut model = media();
model.teardown = true;
let rendered = prettyplease::unparse(&emission(&model));
let compact: String = rendered.chars().filter(|c| !c.is_whitespace()).collect();
assert!(
compact
.contains("fn__ig_says_goodbye<__INGRAPH_NODE__:::ingraph::__private::drive::AsyncTeardown"),
"the bound is what the word buys: {rendered}"
);
assert!(
rendered.contains("__ig_says_goodbye::<Media>"),
"and it is demanded of the declared type itself: {rendered}"
);
}
#[test]
fn a_node_torn_down_by_drop_emits_no_goodbye_audit() {
assert!(
!prettyplease::unparse(&emission(&media())).contains("__ig_says_goodbye"),
"no word, no audit"
);
}
#[test]
fn every_upstream_of_a_fusion_reaches_the_subscription_audit() {
let rendered = prettyplease::unparse(&emission(&fused()));
for upstream in ["media::Frame", "asr::Segment"] {
assert!(
rendered.contains(&format!("__ig_subscribes_to::<{upstream}>")),
"the upstream that is not the parent is still an upstream: {rendered}"
);
}
}
#[test]
fn a_fusion_emits_the_equation_its_lineage_is_checked_by() {
let rendered = prettyplease::unparse(&emission(&fused()));
assert!(
rendered.contains(
"fn(\n <media::Frame as ::ingraph::__private::transform::Transformer>::Key,\n ) -> VideoLineage"
),
"the parent's key in, this node's lineage out: {rendered}"
);
assert!(
rendered.contains("media_id: __ingraph_key.frame"),
"a diverging mirror reads the parent field it was mapped onto: {rendered}"
);
}
#[test]
fn a_fan_ins_lineage_is_a_choice_among_its_upstreams() {
let rendered = prettyplease::unparse(&emission(&fanned()));
assert!(
rendered.contains("pub enum VideoLineage"),
"the ancestry is a choice, not a path: {rendered}"
);
for (variant, node) in [("Frame", "media::Frame"), ("Segment", "asr::Segment")] {
assert!(
rendered.contains(&format!(
"{variant}(<{node} as ::ingraph::__private::transform::Transformer>::Key)"
)),
"each variant carries that upstream's whole key: {rendered}"
);
}
assert!(
!rendered.contains("impl VideoLineage"),
"an enum is built by naming a variant and read by matching on one — no constructor, no \
accessors: {rendered}"
);
}
#[test]
fn a_fan_ins_key_leads_with_the_choice_it_was_injected_with() {
let model = fanned();
let rendered = prettyplease::unparse(&emission(&model));
assert!(
rendered.contains("pub(crate) lineage: VideoLineage"),
"the key column takes a name an address can be spelled with: {rendered}"
);
assert!(
rendered.contains("lineage: record.__ig_lineage__"),
"and it is read out of the field the echo appended: {rendered}"
);
assert_eq!(
model
.fanned_lineage()
.map(|field| quote::ToTokens::to_token_stream(&field).to_string()),
Some("pub (crate) __ig_lineage__ : VideoLineage".to_owned()),
"the mint the echo appends, spelled where it is read back"
);
}
#[test]
fn a_fan_ins_address_grows_a_variant_level() {
let rendered = prettyplease::unparse(&emission(&fanned()));
assert!(
rendered.contains("impl ::ingraph::__private::store::KeySegments for VideoLineage"),
"the choice walks itself: {rendered}"
);
assert!(
rendered.contains("out.push_word(\"Frame\");"),
"the variant's own word is a segment: {rendered}"
);
assert!(
rendered.contains(
"::ingraph::__private::store::KeySegments::segments(&self.lineage, out);\n out.push(&self.id);"
),
"and the key walks the choice, then pushes its own id: {rendered}"
);
}
#[test]
fn a_node_that_designates_no_parent_emits_no_equation() {
assert!(
!prettyplease::unparse(&emission(&video())).contains("__ingraph_key"),
"no designation, no equation"
);
}
#[test]
fn a_node_with_no_storage_mints_no_marker() {
let mut model = media();
model.kind = NodeKind::Operator;
let file = emission(&model);
assert!(
!all_items(&file)
.iter()
.any(|item| matches!(item, syn::Item::Const(named) if named.ident != "_")),
"an operator's emission carries no named const at all"
);
}
#[test]
fn the_address_binding_names_the_emitted_types() {
for (model, lineage) in [
(video_track(), "TrackScope"),
(video(), "VideoLineage"),
(media(), "()"),
] {
let file = emission(&model);
let bound = binding(&file);
assert_eq!(impl_of(bound), model.record.to_string(), "on the RECORD");
assert_eq!(associated(bound, "Key"), model.key.name.to_string());
assert_eq!(associated(bound, "Lineage"), lineage);
}
}
#[test]
fn the_id_capability_is_bound_on_the_record_and_on_its_key() {
for model in [video_track(), video(), media()] {
let file = emission(&model);
let identities: Vec<(String, String)> = trait_impls(&file)
.into_iter()
.filter(|(_, path)| {
path
.segments
.last()
.is_some_and(|segment| segment.ident == "Identifiable")
})
.map(|(item, _)| (impl_of(item), associated(item, "Id")))
.collect();
let id = tight(&model.key.id.ty);
assert_eq!(
identities,
[
(model.record.to_string(), id.clone()),
(model.key.name.to_string(), id)
],
"the record and its key, each binding the id column's declared type verbatim — an alias \
stays an alias — and nothing else identified"
);
}
}
#[test]
fn the_key_walks_its_columns_root_first() {
let mut renamed = video_track();
renamed.key.path[1].name = ident("video");
for (model, pushes) in [
(video_track(), ["media_id", "video_id", "id"].as_slice()),
(renamed, ["media_id", "video", "id"].as_slice()),
(video(), ["media_id", "id"].as_slice()),
(media(), ["id"].as_slice()),
] {
let file = emission(&model);
let walk = path_walk(&file);
assert_eq!(impl_of(walk), model.key.name.to_string(), "on the KEY");
let expected: Vec<String> = pushes
.iter()
.map(|column| format!("out.push(&self.{column});"))
.collect();
assert_eq!(statements(walk), expected);
}
}
fn path_walk(file: &syn::File) -> &syn::ItemImpl {
trait_impls(file)
.into_iter()
.find_map(|(item, path)| {
path
.segments
.last()
.is_some_and(|segment| segment.ident == "KeySegments")
.then_some(item)
})
.expect("the key's path walk is emitted")
}
fn statements(item: &syn::ItemImpl) -> Vec<String> {
methods(item)
.into_iter()
.flat_map(|method| &method.block.stmts)
.map(tight)
.collect()
}
#[test]
fn a_record_binds_its_row_form_only_where_it_persists() {
assert_eq!(
associated(binding(&emission(&persisted())), "Record"),
"Self",
"three databases, one row form: the record they are all projections of"
);
assert_eq!(
associated(binding(&emission(&video_track())), "Record"),
"()",
"and a record no database stores becomes no row"
);
}
#[test]
fn the_two_query_conditions_cut_a_declaration_four_ways() {
for (model, wire, order, why) in [
(
wired(),
"Self",
Some("VideoTrackOrderBy"),
"stored and exposed: both",
),
(
persisted(),
"()",
Some("VideoTrackOrderBy"),
"stored only: an order over the columns, and no face to reach it through",
),
(
wire_only(),
"Self",
None,
"exposed only: a face, and no column an order could name",
),
(video_track(), "()", None, "neither"),
] {
let file = emission(&model);
assert_eq!(associated(binding(&file), "Graphql"), wire, "{why}");
assert_eq!(
order_capability(&file).map(|item| associated(item, "OrderBy")),
order.map(str::to_owned),
"{why}"
);
}
}
#[test]
fn the_query_faces_name_the_models_types_and_not_the_conventions() {
let mut model = wired();
model.order_by = RustSafeName::from_ident(&ident("TrackSort"));
model
.graphql
.as_mut()
.expect("`wired` declares a face")
.filter = RustSafeName::from_ident(&ident("TrackWhere"));
let file = emission(&model);
assert_eq!(
associated(
wire_half(&file, "GraphqlInput").expect("the input half is emitted"),
"Filter"
),
"TrackWhere"
);
assert_eq!(
associated(
order_capability(&file).expect("a stored record carries its order"),
"OrderBy"
),
"TrackSort"
);
}
#[test]
fn a_wire_face_binds_a_carrier_per_half_and_each_half_names_its_types() {
let file = emission(&wired());
let face = wire_face(&file).expect("`wired` declares a face");
assert_eq!(associated(face, "Input"), "VideoTrackGraphqlInput");
assert_eq!(associated(face, "Output"), "VideoTrackGraphqlOutput");
let input = wire_half(&file, "GraphqlInput").expect("the input half is emitted");
assert_eq!(associated(input, "Filter"), "VideoTrackFilter");
assert_eq!(associated(input, "OrderBy"), "VideoTrackOrderBy");
assert_eq!(
associated(
wire_half(&file, "GraphqlOutput").expect("the output half is emitted"),
"Key"
),
"VideoTrackKeyOutput"
);
assert!(
wire_face(&emission(&persisted())).is_none(),
"a declaration with no `graphql(…)` block gets no face impl at all"
);
let unstored = emission(&wire_only());
assert_eq!(
associated(
wire_half(&unstored, "GraphqlInput").expect("the input half is emitted"),
"OrderBy"
),
"()",
"a face over a record stored nowhere has no term type to name"
);
}
fn binding(file: &syn::File) -> &syn::ItemImpl {
trait_impls(file)
.into_iter()
.find_map(|(item, path)| {
path
.segments
.last()
.is_some_and(|segment| segment.ident == "Transformer")
.then_some(item)
})
.expect("the address binding is emitted")
}
fn order_capability(file: &syn::File) -> Option<&syn::ItemImpl> {
wrote(file, "Record")
}
fn wire_face(file: &syn::File) -> Option<&syn::ItemImpl> {
wrote(file, "Graphql")
}
fn wire_half<'a>(file: &'a syn::File, half: &str) -> Option<&'a syn::ItemImpl> {
wrote(file, half)
}
fn wrote<'a>(file: &'a syn::File, name: &str) -> Option<&'a syn::ItemImpl> {
trait_impls(file).into_iter().find_map(|(item, path)| {
path
.segments
.last()
.is_some_and(|segment| segment.ident == name)
.then_some(item)
})
}
fn associated(item: &syn::ItemImpl, name: &str) -> String {
item
.items
.iter()
.find_map(|entry| match entry {
syn::ImplItem::Type(bound) if bound.ident == name => Some(tight(&bound.ty)),
_ => None,
})
.unwrap_or_else(|| panic!("`type {name}` is bound"))
}
#[test]
fn every_emitted_type_carries_exactly_the_five_derives_and_no_other_attribute() {
for model in [video_track(), video(), media()] {
let file = emission(&model);
for item in structs(&file) {
let attrs: Vec<String> = item
.attrs
.iter()
.filter(|attr| !attr.path().is_ident("doc"))
.map(tight)
.collect();
assert_eq!(
attrs,
[
"#[derive(::core::fmt::Debug,::core::clone::Clone,::core::cmp::PartialEq,::core::cmp::Eq,::core::hash::Hash)]"
],
"`{}` carries that and its docs, and nothing else — `non_exhaustive` in particular \
would stop anything outside from calling `new`",
item.ident
);
}
}
}
#[test]
fn the_emission_declares_only_the_authorised_trait_impl() {
for model in [video_track(), video(), media()] {
let file = emission(&model);
let framework = unauthorised_framework_impls(&model, &file);
assert!(
framework.is_empty(),
"`{}` implemented {framework:?}; the framework's trait layer must settle before an \
expansion names it",
model.record
);
let stray: Vec<&syn::Item> = all_items(&file)
.into_iter()
.filter(|item| {
!matches!(
item,
syn::Item::Struct(_) | syn::Item::Impl(_) | syn::Item::Const(_)
)
})
.collect();
assert!(
stray.is_empty(),
"only structs, their inherent impls, and the const those sit in"
);
}
}
#[test]
fn the_impls_live_in_one_anonymous_const_and_the_structs_stay_outside() {
for (model, types) in [(video_track(), 2), (video(), 2), (media(), 1)] {
let impl_count = types + 1 + 1 + 2 + 1 + types * 2 + 2 + 1 + 1;
let file = emission(&model);
let consts: Vec<&syn::ItemConst> = file
.items
.iter()
.filter_map(|item| match item {
syn::Item::Const(item) => Some(item),
_ => None,
})
.collect();
assert_eq!(consts.len(), 2, "the marker, then one wrapper per record");
assert_eq!(
consts[0].ident,
one_storage_marker(&EmissionPrefix::default(), &model.record)
);
assert_eq!(consts[1].ident, "_", "and the wrapper is anonymous");
let top: Vec<&syn::Item> = file.items.iter().collect();
assert_eq!(
top.len(),
types + 2,
"the structs, the marker, then the const"
);
assert!(
top
.iter()
.all(|item| matches!(item, syn::Item::Struct(_) | syn::Item::Const(_))),
"no impl at top level"
);
assert_eq!(structs(&file).len(), types, "the structs are outside");
assert_eq!(impls(&file).len(), impl_count, "the impls are inside");
}
}
#[test]
fn the_impl_walk_descends_into_the_const_wrapper() {
let file = emission(&video_track());
assert!(
!file
.items
.iter()
.any(|item| matches!(item, syn::Item::Impl(_))),
"there is no impl at top level to find"
);
assert_eq!(
inherent(&file).len(),
3,
"the key's, the lineage type's and the record's, all found inside the wrapper"
);
assert_eq!(
trait_impls(&file).len(),
12,
"and the four conversions beside the address binding, its two id impls, the key's path walk, \
the two rows every node states about what it emits, the FACTS a graph root reads it \
through, and the root projection the root-key registry reads instead"
);
assert!(
!method_names(&file).is_empty(),
"and their methods with them"
);
}
#[test]
fn automatically_derived_marks_the_trait_impls_and_only_those() {
for model in [
video_track(),
video(),
media(),
persisted(),
wired(),
referring(),
] {
let file = emission(&model);
let derived = |attrs: &[syn::Attribute]| {
attrs
.iter()
.any(|attr| attr.path().is_ident("automatically_derived"))
};
for (item, path) in trait_impls(&file) {
assert!(
derived(&item.attrs),
"`impl {} for {}` is generated and says so",
tight(path),
tight(&item.self_ty)
);
}
for item in inherent(&file) {
assert!(
!derived(&item.attrs),
"`impl {}` is INHERENT — rustc warns on the attribute there and will make it an error",
tight(&item.self_ty)
);
}
for item in structs(&file) {
assert!(!derived(&item.attrs), "`{}`", item.ident);
}
}
}
#[test]
fn the_emitted_visibility_mirrors_the_source_struct() {
for model in [video_track(), video(), media()] {
for (emission, expected) in [
(emission(&model.clone()), "pub"),
(emission(&private(model)), ""),
] {
for item in structs(&emission) {
assert_eq!(tight(&item.vis), expected, "`{}`", item.ident);
}
for method in inherent(&emission).iter().flat_map(|item| methods(item)) {
assert_eq!(
tight(&method.vis),
expected,
"`{}` is reached exactly as widely as the type it belongs to",
method.sig.ident
);
}
}
}
}
#[test]
fn a_field_is_never_wider_than_the_crate() {
for model in [video_track(), video(), media()] {
let addresses = [
model.key.name.to_string(),
model
.lineage
.as_ref()
.map_or_else(String::new, |lineage| lineage.name.to_string()),
];
let file = emission(&model);
for item in structs(&file) {
let expected = if addresses.contains(&item.ident.to_string()) {
"pub(crate)"
} else {
""
};
for field in named(item) {
assert_eq!(
tight(&field.vis),
expected,
"`{}::{}`",
item.ident,
field.ident.as_ref().expect("named")
);
}
}
}
}
#[test]
fn every_emitted_item_the_lint_covers_is_documented() {
for model in [video_track(), video(), media()] {
let file = emission(&model);
for item in structs(&file) {
assert!(documented(&item.attrs), "`{}` is undocumented", item.ident);
}
for method in inherent(&file).iter().flat_map(|item| methods(item)) {
assert!(
documented(&method.attrs),
"`{}` is undocumented",
method.sig.ident
);
}
}
}
#[test]
fn the_documentation_describes_the_type_not_the_macro() {
let file = emission(&video_track());
let key = structs(&file)[0];
assert!(
docs(&key.attrs).contains("[`VideoTrack`]"),
"the key names the record it addresses: {:?}",
docs(&key.attrs)
);
for (method, expected) in [
("media_id", "The`media_id`stepofthelineagepath."),
(
"media_id_ref",
"The`media_id`stepofthelineagepath,byreference.",
),
("set_media_id", "Setthe`media_id`stepofthelineagepath."),
("with_media_id", "Thesamevaluewithadifferent`media_id`."),
("id_ref", "Therow'sownid,byreference."),
] {
let doc = docs(&key_method(&file, method).attrs);
assert!(doc.contains(expected), "`{method}`: {doc:?}");
}
}
#[test]
fn a_key_is_constructed_by_one_positional_const_new_in_key_order() {
for model in [video_track(), video(), media()] {
let file = emission(&model);
let new = key_method(&file, "new");
assert!(is_const(new), "`new` is const whatever the columns are");
let parameters: Vec<String> = new
.sig
.inputs
.iter()
.map(|input| match input {
syn::FnArg::Typed(typed) => tight(&typed.pat),
syn::FnArg::Receiver(_) => panic!("`new` takes no self"),
})
.collect();
let expected: Vec<String> = model
.key
.columns()
.map(|column| column.name.to_string())
.collect();
assert_eq!(parameters, expected);
}
}
#[test]
fn a_copy_column_gets_a_value_accessor_and_const_mutators() {
let file = emission(&video_track());
let value = key_method(&file, "media_id");
assert!(is_const(value) && !returns_reference(value), "`media_id`");
let borrow = key_method(&file, "media_id_ref");
assert!(
is_const(borrow) && returns_reference(borrow),
"`media_id_ref`"
);
assert!(is_const(key_method(&file, "set_media_id")));
assert!(is_const(key_method(&file, "with_media_id")));
}
#[test]
fn a_plain_column_gets_only_a_ref_accessor_and_non_const_mutators() {
let file = emission(&video_track());
let borrow = key_method(&file, "video_id_ref");
assert!(
is_const(borrow) && returns_reference(borrow),
"`video_id_ref`"
);
assert!(
!key_methods(&file)
.iter()
.any(|method| method.sig.ident == "video_id"),
"an unmarked column has no by-value accessor"
);
assert!(!is_const(key_method(&file, "set_video_id")));
assert!(!is_const(key_method(&file, "with_video_id")));
}
#[test]
fn the_marker_only_adds_the_value_accessor() {
let plain = emission(&video());
let mut marked = video();
marked
.lineage
.as_mut()
.expect("a child has a path")
.path_mut()[0]
.project = Projection::Copied;
marked.key.path[0].project = Projection::Copied;
let marked = emission(&marked);
assert!(method_names(&plain).contains(&"media_id_ref".to_owned()));
assert!(method_names(&marked).contains(&"media_id_ref".to_owned()));
assert!(!method_names(&plain).contains(&"media_id".to_owned()));
assert!(method_names(&marked).contains(&"media_id".to_owned()));
let gained: Vec<String> = method_names(&marked)
.into_iter()
.filter(|name| !method_names(&plain).contains(name))
.collect();
assert_eq!(
gained,
["media_id", "media_id"],
"nothing is renamed or removed — and the marker describes the COLUMN, so it reaches both the \
key and the lineage type, which `media_id` is a column of"
);
}
#[test]
fn every_with_carries_must_use_and_nothing_else_does() {
for model in [video_track(), video(), media()] {
let file = emission(&model);
for method in inherent(&file).iter().flat_map(|item| methods(item)) {
let name = method.sig.ident.to_string();
assert_eq!(
must_use(method),
name.starts_with("with_"),
"`{name}` and `#[must_use]`"
);
}
}
}
#[test]
fn the_method_set_is_new_then_each_columns_family() {
let file = emission(&video_track());
assert_eq!(
methods_of(&file, "TrackAddress"),
[
"new",
"media_id",
"media_id_ref",
"set_media_id",
"with_media_id",
"video_id_ref",
"set_video_id",
"with_video_id",
"id_ref",
"set_id",
"with_id",
]
);
assert_eq!(
methods_of(&file, "TrackScope"),
[
"new",
"media_id",
"media_id_ref",
"set_media_id",
"with_media_id",
"video_id_ref",
"set_video_id",
"with_video_id",
],
"the same path without the id"
);
assert_eq!(
methods_of(&emission(&media()), "MediaKey"),
["new", "id", "id_ref", "set_id", "with_id"],
"a root with a marked id"
);
}
#[test]
fn the_enumeration_names_exactly_the_methods_the_emission_declares() {
for model in [
video_track(),
video(),
media(),
persisted(),
whole_row(),
wired(),
ordered(),
] {
let file = emission(&model);
let declared: Vec<(String, String)> = inherent(&file)
.into_iter()
.flat_map(|item| {
let owner = owner_of(item);
methods(item)
.into_iter()
.map(move |method| (owner.clone(), method.sig.ident.to_string()))
})
.collect();
let named: Vec<(String, String)> = model
.emitted_methods()
.iter()
.map(|method| (method.owner_name.to_string(), method.name.to_string()))
.collect();
assert_eq!(named, declared, "`{}`", model.record);
}
}
#[test]
fn the_enumeration_names_exactly_the_types_the_emission_declares() {
for model in [
video_track(),
video(),
media(),
persisted(),
whole_row(),
wired(),
wire_only(),
ordered(),
] {
let declared = scoped_types(&emission(&model));
assert!(!declared.is_empty(), "`{}` emits types", model.record);
let named: Vec<String> = model
.emitted_types()
.iter()
.map(|declared| declared.name.to_string())
.collect();
assert_eq!(named, declared, "`{}`", model.record);
}
}
#[test]
fn the_record_gets_an_impl_with_no_constructor() {
for model in [video_track(), video(), media()] {
let file = emission(&model);
let record = model.record.to_string();
let names = methods_of(&file, &record);
assert!(!names.is_empty(), "`{record}` has an impl");
assert!(
!names.contains(&"new".to_owned()),
"`{record}` has no generated constructor: {names:?}"
);
}
}
#[test]
fn identity_fields_get_getters_only_on_the_record() {
let file = emission(&video_track());
assert_eq!(
methods_of(&file, "VideoTrack"),
[
"media_id",
"media_id_ref",
"video_id_ref",
"id_ref",
"checksum_ref",
"set_checksum",
"with_checksum",
"chapters_slice",
"set_chapters",
"with_chapters",
"cover_id_ref",
"set_cover_id",
"with_cover_id",
]
);
}
#[test]
fn marked_fields_get_the_projected_shapes() {
let file = emission(&video());
let record = "Video";
assert_eq!(
returns(method_of(&file, record, "chapters_slice")),
"&[<Vec<Uuid7>as::ingraph::__private::project::Repeated>::Item]"
);
assert_eq!(
returns(method_of(&file, record, "cover_id_ref")),
"::core::option::Option<&<Option<Uuid7>as::ingraph::__private::project::Optional>::Item>"
);
assert_eq!(
returns(method_of(&file, record, "checksum_ref")),
"&u64",
"and an unmarked field takes the plain borrow — nothing is inferred"
);
}
#[test]
fn a_projected_accessor_is_not_const_but_a_plain_one_is() {
let file = emission(&video());
assert!(!is_const(method_of(&file, "Video", "chapters_slice")));
assert!(!is_const(method_of(&file, "Video", "cover_id_ref")));
assert!(is_const(method_of(&file, "Video", "checksum_ref")));
assert!(is_const(method_of(&file, "Video", "media_id_ref")));
}
#[test]
fn an_aliased_collection_type_still_projects() {
let mut model = video();
model.fields[3].column.ty = ty("Chapters");
model.fields[4].column.ty = ty("MaybeCover");
let file = emission(&model);
assert_eq!(
returns(method_of(&file, "Video", "chapters_slice")),
"&[<Chaptersas::ingraph::__private::project::Repeated>::Item]"
);
assert_eq!(
returns(method_of(&file, "Video", "cover_id_ref")),
"::core::option::Option<&<MaybeCoveras::ingraph::__private::project::Optional>::Item>"
);
}
#[test]
fn the_projection_traits_are_reached_through_the_models_crate_path() {
let mut model = video();
model.krate = syn::parse_quote!(shim::vendored::ingraph);
let file = emission(&model);
assert_eq!(
returns(method_of(&file, "Video", "chapters_slice")),
"&[<Vec<Uuid7>asshim::vendored::ingraph::__private::project::Repeated>::Item]"
);
}
#[test]
fn a_shelf_path_names_as_many_modules_as_the_item_lives_under() {
let model = video();
assert_eq!(
tight(model.framework(&["graphql"], "ToGraphqlFilter")),
"::ingraph::__private::graphql::ToGraphqlFilter"
);
assert_eq!(
tight(model.framework(&["comparison", "sql"], "SqlScalarComparison")),
"::ingraph::__private::comparison::sql::SqlScalarComparison"
);
}
#[test]
fn every_framework_path_goes_through_a_private_module() {
for mut model in [video_track(), video(), media(), wired()] {
for krate in [
syn::parse_quote!(::ingraph),
syn::parse_quote!(shim::vendored::ingraph),
] {
model.krate = krate;
let ill_formed = framework_paths_not_through_a_private_module(&model);
assert!(
ill_formed.is_empty(),
"`{}` reaches the framework outside `__private::<module…>`: {ill_formed:?}",
model.record
);
}
}
}
#[test]
fn the_ingraph_roots_emission_goes_through_the_shelf_too() {
for krate in [
syn::parse_quote!(::ingraph),
syn::parse_quote!(shim::vendored::ingraph),
] {
let model = crate::graph::GraphModel {
krate,
vis: syn::parse_quote!(pub),
name: syn::parse_quote!(App),
nodes: vec![syn::parse_quote!(media::Video), syn::parse_quote!(Scene)],
mounts: vec![syn::parse_quote!(videos), syn::parse_quote!(scenes)],
queried: Vec::new(),
interfaces: Vec::new(),
fused: Vec::new(),
resources: vec![
crate::catalog::ResourceField {
mount: syn::parse_quote!(egemma),
ty: syn::parse_quote!(models::Egemma),
source: crate::catalog::ResourceSource::Section,
teardown: false,
},
crate::catalog::ResourceField {
mount: syn::parse_quote!(cache),
ty: syn::parse_quote!(Cache),
source: crate::catalog::ResourceSource::Initializer(syn::parse_quote!(boot::cache)),
teardown: true,
},
crate::catalog::ResourceField {
mount: syn::parse_quote!(pool),
ty: syn::parse_quote!(Pool),
source: crate::catalog::ResourceSource::Prepare,
teardown: false,
},
],
origins: Vec::new(),
engines: Vec::new(),
retired: None,
generations: None,
};
let root = model
.krate
.segments
.last()
.expect("a crate path has a last segment")
.ident
.clone();
let ill_formed = ill_formed_shelf_paths(model.emit(), &root);
assert!(
ill_formed.is_empty(),
"the graph root reaches the framework outside `__private::<module…>`: {ill_formed:?}"
);
}
}
#[test]
fn shelf_refusals() {
let root = ident("ingraph");
let scan = |stream: proc_macro2::TokenStream| ill_formed_shelf_paths(stream, &root);
assert_eq!(
scan(quote::quote!(::ingraph::ToGraphqlFilter)).len(),
1,
"a path that skips `__private` entirely"
);
assert_eq!(
scan(quote::quote!(::ingraph::__private::ToGraphqlFilter)).len(),
1,
"and one that names an item directly beneath it — the flattened shape, which is what the \
module segment exists to prevent"
);
assert_eq!(
scan(quote::quote!(::ingraph::graphql::lower::ToGraphqlFilter)).len(),
1,
"a path of the right DEPTH through the wrong module is still refused — depth is not what is \
being checked, `__private` is, and reaching an item where it really lives is exactly what the \
shelf exists to stop an expansion doing"
);
assert!(
scan(quote::quote!(
::ingraph::__private::graphql::ToGraphqlFilter
))
.is_empty(),
"one module segment is well formed"
);
assert!(
scan(quote::quote!(
::ingraph::__private::comparison::sql::SqlScalarComparison
))
.is_empty(),
"and so is a family nested one deeper, which is how the shelf mirrors a module inside a module"
);
}
fn framework_paths_not_through_a_private_module(model: &RecordModel) -> Vec<String> {
let root = &model
.krate
.segments
.last()
.expect("a crate path has a last segment")
.ident;
ill_formed_shelf_paths(model.emit(), root)
}
fn ill_formed_shelf_paths(stream: proc_macro2::TokenStream, root: &syn::Ident) -> Vec<String> {
let tokens = flat_tokens(stream);
let colon = |at: usize| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ':');
let named = |at: usize, name: &str| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Ident(id)) if id == name);
let any_ident = |at: usize| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Ident(_)));
let well_formed = |at: usize| {
if !(colon(at + 1) && colon(at + 2) && named(at + 3, "__private")) {
return false;
}
let mut segments = 0;
let mut cursor = at + 3;
while colon(cursor + 1) && colon(cursor + 2) && any_ident(cursor + 3) {
segments += 1;
cursor += 3;
}
segments >= 2
};
(0..tokens.len())
.filter(|at| named(*at, &root.to_string()))
.filter(|at| !well_formed(*at))
.map(|at| {
tokens[at..(at + 10).min(tokens.len())]
.iter()
.map(ToString::to_string)
.collect()
})
.collect()
}
#[test]
fn no_emitted_path_names_a_per_dialect_alias_module() {
for mut model in [video_track(), video(), media(), wired()] {
for krate in [
syn::parse_quote!(::ingraph),
syn::parse_quote!(shim::vendored::ingraph),
] {
model.krate = krate;
let named = per_dialect_alias_paths(model.emit());
assert!(
named.is_empty(),
"`{}` reaches a per-dialect alias module: {named:?}; an expansion writes the full form",
model.record
);
}
}
}
#[test]
fn per_dialect_alias_refusals() {
assert_eq!(
per_dialect_alias_paths(quote::quote!(
::ingraph::__private::comparison::sql::postgres::ScalarComparison
))
.len(),
1,
"the shelf spelling"
);
assert_eq!(
per_dialect_alias_paths(quote::quote!(
::ingraph::comparison::sql::sqlite::TextComparison
))
.len(),
1,
"and the public one, which the shelf rule would let through with its own error"
);
assert!(
per_dialect_alias_paths(quote::quote!(
::ingraph::__private::comparison::sql::SqlScalarComparison
))
.is_empty(),
"the full form is what an expansion writes"
);
assert!(
per_dialect_alias_paths(quote::quote!(::ingraph::__private::sqlx::Postgres)).is_empty(),
"naming the dialect TYPE is not naming its alias module, and `sqlx` is not `sql`"
);
}
fn per_dialect_alias_paths(stream: proc_macro2::TokenStream) -> Vec<String> {
const DIALECTS: [&str; 3] = ["sqlite", "postgres", "mysql"];
let tokens = flat_tokens(stream);
let colon = |at: usize| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ':');
let named = |at: usize, name: &str| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Ident(id)) if id == name);
(0..tokens.len())
.filter(|at| named(*at, "sql"))
.filter(|at| {
colon(at + 1) && colon(at + 2) && DIALECTS.iter().any(|dialect| named(at + 3, dialect))
})
.map(|at| {
tokens[at..(at + 7).min(tokens.len())]
.iter()
.map(ToString::to_string)
.collect()
})
.collect()
}
fn flat_tokens(stream: proc_macro2::TokenStream) -> Vec<proc_macro2::TokenTree> {
fn flatten(stream: proc_macro2::TokenStream, into: &mut Vec<proc_macro2::TokenTree>) {
for tree in stream {
match tree {
proc_macro2::TokenTree::Group(group) => flatten(group.stream(), into),
other => into.push(other),
}
}
}
let mut tokens = Vec::new();
flatten(stream, &mut tokens);
tokens
}
#[test]
fn every_emitted_method_is_inline_but_not_inline_always() {
for model in [video_track(), video(), media()] {
let file = emission(&model);
for method in impls(&file).iter().flat_map(|item| methods(item)) {
let attrs: Vec<String> = method
.attrs
.iter()
.filter(|attr| !attr.path().is_ident("doc"))
.map(tight)
.collect();
assert!(
attrs.contains(&"#[inline]".to_owned()),
"`{}`: {attrs:?}",
method.sig.ident
);
assert!(
!attrs.iter().any(|attr| attr.contains("always")),
"`{}`: {attrs:?}",
method.sig.ident
);
}
}
}
#[test]
fn the_argument_count_allow_rides_every_constructor_and_nothing_wider() {
const ALLOW: &str = "#[allow(clippy::too_many_arguments)]";
let carries = |attrs: &[syn::Attribute]| attrs.iter().any(|attr| tight(attr) == ALLOW);
for model in [video_track(), video(), media(), persisted()] {
let file = emission(&model);
for item in all_items(&file) {
let (attrs, what) = match item {
syn::Item::Impl(item) => (&item.attrs, format!("`impl {}`", impl_of(item))),
syn::Item::Struct(item) => (&item.attrs, format!("`{}`", item.ident)),
syn::Item::Const(item) => (&item.attrs, "the anonymous const".to_owned()),
_ => continue,
};
assert!(!carries(attrs), "{what} carries the allow");
}
let mut constructors = 0;
for method in impls(&file).iter().flat_map(|item| methods(item)) {
let constructor = method.sig.ident == "new";
constructors += usize::from(constructor);
assert_eq!(
carries(&method.attrs),
constructor,
"`{}` and the argument-count allow",
method.sig.ident
);
}
assert!(
constructors > 0,
"an emission declares a constructor at all"
);
}
}
#[test]
fn a_fields_type_is_the_models_own_type_verbatim() {
let mut model = video();
model.key.id.ty = ty("MediaFileId");
let file = emission(&model);
let key = structs(&file)[0];
let types: Vec<String> = named(key).iter().map(|f| tight(&f.ty)).collect();
assert_eq!(types, ["Uuid7", "MediaFileId"]);
}
#[test]
fn the_fixture_shapes_render_exactly() {
assert_eq!(prettyplease::unparse(&emission(&media())), MEDIA);
assert_eq!(
prettyplease::unparse(&emission(&private(video()))),
VIDEO_PRIVATE,
"the same shape without a `pub` on its source struct"
);
}
const MEDIA: &str = "\
/// The address of a [`Media`] row: its own id.
#[derive(
::core::fmt::Debug,
::core::clone::Clone,
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::hash::Hash
)]
pub struct MediaKey {
pub(crate) id: Uuid7,
}
#[doc(hidden)]
#[allow(dead_code, non_upper_case_globals)]
const __ig_Media_holds_one_storage: () = ();
const _: () = {
impl MediaKey {
/// Construct an address from the row's own id.
#[allow(clippy::too_many_arguments)]
#[inline]
pub const fn new(id: Uuid7) -> Self {
Self { id }
}
/// The row's own id.
#[inline]
pub const fn id(&self) -> Uuid7 {
self.id
}
/// The row's own id, by reference.
#[inline]
pub const fn id_ref(&self) -> &Uuid7 {
&self.id
}
/// Set the row's own id.
#[inline]
pub const fn set_id(&mut self, value: Uuid7) -> &mut Self {
self.id = value;
self
}
/// The same value with a different `id`.
#[must_use]
#[inline]
pub const fn with_id(mut self, value: Uuid7) -> Self {
self.id = value;
self
}
}
impl Media {
/// The `id` field of this [`Media`].
#[inline]
pub const fn id(&self) -> Uuid7 {
self.id
}
/// The `id` field of this [`Media`], by reference.
#[inline]
pub const fn id_ref(&self) -> &Uuid7 {
&self.id
}
/// The `checksum` field of this [`Media`], by reference.
#[inline]
pub const fn checksum_ref(&self) -> &u64 {
&self.checksum
}
/// Set the `checksum` field of this [`Media`].
#[inline]
pub fn set_checksum(&mut self, value: u64) -> &mut Self {
self.checksum = value;
self
}
/// The same value with a different `checksum`.
#[must_use]
#[inline]
pub fn with_checksum(mut self, value: u64) -> Self {
self.checksum = value;
self
}
/// The `chapters` field of this [`Media`], as a slice.
#[inline]
pub fn chapters_slice(
&self,
) -> &[<Vec<Uuid7> as ::ingraph::__private::project::Repeated>::Item] {
::ingraph::__private::project::Repeated::as_slice(&self.chapters)
}
/// Set the `chapters` field of this [`Media`].
#[inline]
pub fn set_chapters(&mut self, value: Vec<Uuid7>) -> &mut Self {
self.chapters = value;
self
}
/// The same value with a different `chapters`.
#[must_use]
#[inline]
pub fn with_chapters(mut self, value: Vec<Uuid7>) -> Self {
self.chapters = value;
self
}
/// The `cover_id` field of this [`Media`], by reference.
#[inline]
pub fn cover_id_ref(
&self,
) -> ::core::option::Option<
&<Option<Uuid7> as ::ingraph::__private::project::Optional>::Item,
> {
::ingraph::__private::project::Optional::as_option(&self.cover_id)
}
/// Set the `cover_id` field of this [`Media`].
#[inline]
pub fn set_cover_id(&mut self, value: Option<Uuid7>) -> &mut Self {
self.cover_id = value;
self
}
/// The same value with a different `cover_id`.
#[must_use]
#[inline]
pub fn with_cover_id(mut self, value: Option<Uuid7>) -> Self {
self.cover_id = value;
self
}
}
const _: fn() = ::ingraph::__private::transform::ids_are_keys::<Uuid7>;
#[automatically_derived]
impl ::ingraph::__private::transform::Identifiable for Media {
type Id = Uuid7;
#[inline]
fn id_ref(&self) -> &Uuid7 {
&self.id
}
}
#[automatically_derived]
impl ::ingraph::__private::transform::Transformer for Media {
type Key = MediaKey;
type Lineage = ();
type Record = ();
type Graphql = ();
#[inline]
fn key(&self) -> MediaKey {
<MediaKey as ::core::convert::From<&Media>>::from(self)
}
}
#[automatically_derived]
impl ::ingraph::__private::transform::Identifiable for MediaKey {
type Id = Uuid7;
#[inline]
fn id_ref(&self) -> &Uuid7 {
&self.id
}
}
#[automatically_derived]
impl ::ingraph::__private::store::KeySegments for MediaKey {
#[inline]
fn segments(&self, out: &mut ::ingraph::__private::store::Segments) {
out.push(&self.id);
}
}
#[automatically_derived]
impl ::core::convert::From<Media> for MediaKey {
#[inline]
fn from(record: Media) -> Self {
Self { id: record.id }
}
}
#[automatically_derived]
impl<'a> ::core::convert::From<&'a Media> for MediaKey {
#[inline]
fn from(record: &'a Media) -> Self {
Self {
id: ::core::clone::Clone::clone(&record.id),
}
}
}
#[automatically_derived]
impl ::ingraph::__private::operator::Emits for Media {
type Out = Self;
}
#[automatically_derived]
impl ::ingraph::__private::operator::SoleProduct for Media {}
#[automatically_derived]
impl ::ingraph::__private::drive::Declared for Media {
/// What a [`Media`]'s outputs become — read off the kind it was declared under.
const EFFECT: ::ingraph::__private::drive::Effect = ::ingraph::__private::drive::Effect::Lands;
/// Whether a [`Media`] holds a write lane of its own — read off the same kind.
const HOLDS_LANE: bool = true;
/// Every upstream a [`Media`] draws from, in declaration order.
const UPSTREAMS: &'static [::ingraph::__private::drive::Upstream] = &[];
/// Every store a [`Media`] granted itself the right to write, in declaration order.
const GRANTS: &'static [::ingraph::__private::drive::Grant] = &[];
type Channels = ::ingraph::__private::drive::Unchanneled;
type Options = ();
/// A [`Media`] wrote no `stream`, so its body wears the BUFFERED pair — an `accept` per delivery, mounted at `Blueprint::node`.
type Pair = ::ingraph::__private::drive::Buffered;
/// A [`Media`] emits ONE thing, so it publishes through the framework's own fan-out set — N edges of that one product, the copy taken at the set rather than asked of any driver.
type Wires<__INGRAPH_OUT__> = ::ingraph::__private::drive::Downstream<
__INGRAPH_OUT__,
>;
/// A [`Media`] wrote no `attributed`, so it attributes its outputs to nothing — the unit projection, whose `Attributes` impl is the empty program and whose value is zero-sized. Its observations stay counter-grade, which is the shipped posture for every node that emits a payload with no declared root. The product parameter is the attributed road's and is unread here.
type Attribution<__INGRAPH_OUT__> = ();
/// A [`Media`] wrote no mode word, so its `accept` is the blocking face's — an `Operator` body, called by either engine and answering without a future.
type Mode = ::ingraph::__private::operator::Block;
}
#[automatically_derived]
impl ::ingraph::__private::drive::Attributes<Media>
for ::ingraph::__private::drive::RootProjection<Media> {
/// This root family's own name, read off the root type rather than off a column name so that every record sharing a root agrees on it without saying so.
const FAMILY: &'static str = \"uuid7\";
/// Which root key a [`Media`] descends from — its key's FIRST column, which is the `id` field. The root-key registry tables one machine per family, and this is what tells it which family a record of this type belongs to.
type Root = Uuid7;
#[inline]
fn root(&self, record: &Media) -> Self::Root {
::core::clone::Clone::clone(&record.id)
}
#[inline]
fn observe(
&self,
_root: &Self::Root,
_worker: &::ingraph::__private::drive::NodeName,
_arrival: &::ingraph::__private::drive::Arrival,
) {}
}
};
";
const VIDEO_PRIVATE: &str = "\
/// The address of a [`Video`] row: its lineage path followed by its own id.
#[derive(
::core::fmt::Debug,
::core::clone::Clone,
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::hash::Hash
)]
struct VideoKey {
pub(crate) media_id: Uuid7,
pub(crate) id: Uuid7,
}
/// The path from the root to a [`Video`] row, root-first.
#[derive(
::core::fmt::Debug,
::core::clone::Clone,
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::hash::Hash
)]
struct VideoLineage {
pub(crate) media_id: Uuid7,
}
#[doc(hidden)]
#[allow(dead_code, non_upper_case_globals)]
const __ig_Video_holds_one_storage: () = ();
const _: () = {
impl VideoKey {
/// Construct an address from its lineage path and the row's own id.
#[allow(clippy::too_many_arguments)]
#[inline]
const fn new(media_id: Uuid7, id: Uuid7) -> Self {
Self { media_id, id }
}
/// The `media_id` step of the lineage path, by reference.
#[inline]
const fn media_id_ref(&self) -> &Uuid7 {
&self.media_id
}
/// Set the `media_id` step of the lineage path.
#[inline]
fn set_media_id(&mut self, value: Uuid7) -> &mut Self {
self.media_id = value;
self
}
/// The same value with a different `media_id`.
#[must_use]
#[inline]
fn with_media_id(mut self, value: Uuid7) -> Self {
self.media_id = value;
self
}
/// The row's own id, by reference.
#[inline]
const fn id_ref(&self) -> &Uuid7 {
&self.id
}
/// Set the row's own id.
#[inline]
fn set_id(&mut self, value: Uuid7) -> &mut Self {
self.id = value;
self
}
/// The same value with a different `id`.
#[must_use]
#[inline]
fn with_id(mut self, value: Uuid7) -> Self {
self.id = value;
self
}
}
impl VideoLineage {
/// Construct a path from its steps, root-first.
#[allow(clippy::too_many_arguments)]
#[inline]
const fn new(media_id: Uuid7) -> Self {
Self { media_id }
}
/// The `media_id` step of the lineage path, by reference.
#[inline]
const fn media_id_ref(&self) -> &Uuid7 {
&self.media_id
}
/// Set the `media_id` step of the lineage path.
#[inline]
fn set_media_id(&mut self, value: Uuid7) -> &mut Self {
self.media_id = value;
self
}
/// The same value with a different `media_id`.
#[must_use]
#[inline]
fn with_media_id(mut self, value: Uuid7) -> Self {
self.media_id = value;
self
}
}
impl Video {
/// The `media_id` field of this [`Video`], by reference.
#[inline]
const fn media_id_ref(&self) -> &Uuid7 {
&self.media_id
}
/// The `id` field of this [`Video`], by reference.
#[inline]
const fn id_ref(&self) -> &Uuid7 {
&self.id
}
/// The `checksum` field of this [`Video`], by reference.
#[inline]
const fn checksum_ref(&self) -> &u64 {
&self.checksum
}
/// Set the `checksum` field of this [`Video`].
#[inline]
fn set_checksum(&mut self, value: u64) -> &mut Self {
self.checksum = value;
self
}
/// The same value with a different `checksum`.
#[must_use]
#[inline]
fn with_checksum(mut self, value: u64) -> Self {
self.checksum = value;
self
}
/// The `chapters` field of this [`Video`], as a slice.
#[inline]
fn chapters_slice(
&self,
) -> &[<Vec<Uuid7> as ::ingraph::__private::project::Repeated>::Item] {
::ingraph::__private::project::Repeated::as_slice(&self.chapters)
}
/// Set the `chapters` field of this [`Video`].
#[inline]
fn set_chapters(&mut self, value: Vec<Uuid7>) -> &mut Self {
self.chapters = value;
self
}
/// The same value with a different `chapters`.
#[must_use]
#[inline]
fn with_chapters(mut self, value: Vec<Uuid7>) -> Self {
self.chapters = value;
self
}
/// The `cover_id` field of this [`Video`], by reference.
#[inline]
fn cover_id_ref(
&self,
) -> ::core::option::Option<
&<Option<Uuid7> as ::ingraph::__private::project::Optional>::Item,
> {
::ingraph::__private::project::Optional::as_option(&self.cover_id)
}
/// Set the `cover_id` field of this [`Video`].
#[inline]
fn set_cover_id(&mut self, value: Option<Uuid7>) -> &mut Self {
self.cover_id = value;
self
}
/// The same value with a different `cover_id`.
#[must_use]
#[inline]
fn with_cover_id(mut self, value: Option<Uuid7>) -> Self {
self.cover_id = value;
self
}
}
const _: fn() = ::ingraph::__private::transform::ids_are_keys::<Uuid7>;
#[automatically_derived]
impl ::ingraph::__private::transform::Identifiable for Video {
type Id = Uuid7;
#[inline]
fn id_ref(&self) -> &Uuid7 {
&self.id
}
}
#[automatically_derived]
impl ::ingraph::__private::transform::Transformer for Video {
type Key = VideoKey;
type Lineage = VideoLineage;
type Record = ();
type Graphql = ();
#[inline]
fn key(&self) -> VideoKey {
<VideoKey as ::core::convert::From<&Video>>::from(self)
}
}
#[automatically_derived]
impl ::ingraph::__private::transform::Identifiable for VideoKey {
type Id = Uuid7;
#[inline]
fn id_ref(&self) -> &Uuid7 {
&self.id
}
}
#[automatically_derived]
impl ::ingraph::__private::store::KeySegments for VideoKey {
#[inline]
fn segments(&self, out: &mut ::ingraph::__private::store::Segments) {
out.push(&self.media_id);
out.push(&self.id);
}
}
#[automatically_derived]
impl ::core::convert::From<Video> for VideoKey {
#[inline]
fn from(record: Video) -> Self {
Self {
media_id: record.media_id,
id: record.id,
}
}
}
#[automatically_derived]
impl<'a> ::core::convert::From<&'a Video> for VideoKey {
#[inline]
fn from(record: &'a Video) -> Self {
Self {
media_id: ::core::clone::Clone::clone(&record.media_id),
id: ::core::clone::Clone::clone(&record.id),
}
}
}
#[automatically_derived]
impl ::core::convert::From<Video> for VideoLineage {
#[inline]
fn from(record: Video) -> Self {
Self { media_id: record.media_id }
}
}
#[automatically_derived]
impl<'a> ::core::convert::From<&'a Video> for VideoLineage {
#[inline]
fn from(record: &'a Video) -> Self {
Self {
media_id: ::core::clone::Clone::clone(&record.media_id),
}
}
}
#[automatically_derived]
impl ::ingraph::__private::operator::Emits for Video {
type Out = Self;
}
#[automatically_derived]
impl ::ingraph::__private::operator::SoleProduct for Video {}
#[automatically_derived]
impl ::ingraph::__private::drive::Declared for Video {
/// What a [`Video`]'s outputs become — read off the kind it was declared under.
const EFFECT: ::ingraph::__private::drive::Effect = ::ingraph::__private::drive::Effect::Lands;
/// Whether a [`Video`] holds a write lane of its own — read off the same kind.
const HOLDS_LANE: bool = true;
/// Every upstream a [`Video`] draws from, in declaration order.
const UPSTREAMS: &'static [::ingraph::__private::drive::Upstream] = &[];
/// Every store a [`Video`] granted itself the right to write, in declaration order.
const GRANTS: &'static [::ingraph::__private::drive::Grant] = &[];
type Channels = ::ingraph::__private::drive::Unchanneled;
type Options = ();
/// A [`Video`] wrote no `stream`, so its body wears the BUFFERED pair — an `accept` per delivery, mounted at `Blueprint::node`.
type Pair = ::ingraph::__private::drive::Buffered;
/// A [`Video`] emits ONE thing, so it publishes through the framework's own fan-out set — N edges of that one product, the copy taken at the set rather than asked of any driver.
type Wires<__INGRAPH_OUT__> = ::ingraph::__private::drive::Downstream<
__INGRAPH_OUT__,
>;
/// A [`Video`] wrote no `attributed`, so it attributes its outputs to nothing — the unit projection, whose `Attributes` impl is the empty program and whose value is zero-sized. Its observations stay counter-grade, which is the shipped posture for every node that emits a payload with no declared root. The product parameter is the attributed road's and is unread here.
type Attribution<__INGRAPH_OUT__> = ();
/// A [`Video`] wrote no mode word, so its `accept` is the blocking face's — an `Operator` body, called by either engine and answering without a future.
type Mode = ::ingraph::__private::operator::Block;
}
#[automatically_derived]
impl ::ingraph::__private::drive::Attributes<Video>
for ::ingraph::__private::drive::RootProjection<Video> {
/// This root family's own name, read off the root type rather than off a column name so that every record sharing a root agrees on it without saying so.
const FAMILY: &'static str = \"uuid7\";
/// Which root key a [`Video`] descends from — its key's FIRST column, which is the `media_id` field. The root-key registry tables one machine per family, and this is what tells it which family a record of this type belongs to.
type Root = Uuid7;
#[inline]
fn root(&self, record: &Video) -> Self::Root {
::core::clone::Clone::clone(&record.media_id)
}
#[inline]
fn observe(
&self,
_root: &Self::Root,
_worker: &::ingraph::__private::drive::NodeName,
_arrival: &::ingraph::__private::drive::Arrival,
) {}
}
};
";
use crate::{
model::{
AliasOptions, Conversion, DatabaseBackend, DatabaseKind, MongoDatabase, MySqlDatabase, Persist,
PersistColumn, PostgresDatabase, SqliteDatabase, Storage, default_row_name,
},
name::RustSafeName,
};
fn persist_column(source: &str, name: &str, ty: syn::Type) -> PersistColumn {
PersistColumn {
source: ident(source),
name: RustSafeName::new(name, proc_macro2::Span::call_site()),
domain: ty,
stored: None,
copy: false,
edge: false,
nullable: false,
indexed: false,
unique: false,
flatten: false,
from: Conversion::Default,
into: Conversion::Default,
}
}
fn stored(record: &syn::Ident, kind: DatabaseKind, columns: Vec<PersistColumn>) -> DatabaseBackend {
let name = default_row_name(record, kind);
let storage = Storage {
comparison: default_comparison_name(&name),
name,
from: Conversion::Default,
into: Conversion::Default,
columns,
fills: Vec::new(),
aliases: AliasOptions::default(),
};
match kind {
DatabaseKind::Sqlite => DatabaseBackend::Sqlite(SqliteDatabase {
table: None,
schema: None,
uniques: Vec::new(),
storage,
}),
DatabaseKind::Postgres => DatabaseBackend::Postgres(PostgresDatabase {
table: None,
schema: None,
uniques: Vec::new(),
storage,
}),
DatabaseKind::Mysql => DatabaseBackend::MySql(MySqlDatabase {
table: None,
schema: None,
uniques: Vec::new(),
storage,
}),
DatabaseKind::Mongo => DatabaseBackend::Mongo(MongoDatabase {
collection: None,
storage,
}),
}
}
fn storage_of(database: &mut DatabaseBackend) -> &mut Storage {
match database {
DatabaseBackend::Sqlite(db) => &mut db.storage,
DatabaseBackend::Postgres(db) => &mut db.storage,
DatabaseBackend::MySql(db) => &mut db.storage,
DatabaseBackend::Mongo(db) => &mut db.storage,
}
}
fn fallible(path: syn::Path) -> Conversion {
Conversion::Fallible(FallibleConversion { path, escape: None })
}
fn path(rendered: &str) -> syn::Path {
syn::parse_str(rendered).expect("a path")
}
fn persisted() -> RecordModel {
let mut model = model("VideoTrack", &["media_id", "video_id"], "id");
let record = model.record.clone();
let bit_rate = || persist_column("checksum", "bitrate", ty("u64"));
let cover = || persist_column("cover_id", "cover_id", generic("Option", "Uuid7"));
let sqlite = stored(&record, DatabaseKind::Sqlite, vec![bit_rate(), cover()]);
let mut postgres = stored(&record, DatabaseKind::Postgres, vec![bit_rate(), cover()]);
let postgres_storage = storage_of(&mut postgres);
postgres_storage.name = ident("VideoTrackRecord");
postgres_storage.comparison = default_comparison_name(&ident("VideoTrackRecord"));
postgres_storage.columns[0].name =
RustSafeName::new("bit_rate_v2", proc_macro2::Span::call_site());
postgres_storage.columns[0].stored = Some(ty("BeU64"));
postgres_storage.columns[0].copy = true;
postgres_storage.columns[0].indexed = true;
postgres_storage.columns[0].from = Conversion::Infallible(path("path::to::store"));
postgres_storage.columns[0].into = fallible(path("path::to::raise"));
let mongo = stored(&record, DatabaseKind::Mongo, vec![bit_rate(), cover()]);
model.persist = Some(Persist {
backends: vec![sqlite, postgres, mongo],
table: Some(RustSafeName::new(
"video_tracks",
proc_macro2::Span::call_site(),
)),
});
model
}
pub(crate) fn whole_row() -> RecordModel {
let mut model = model("Media", &[], "id");
let record = model.record.clone();
let columns = model
.fields
.iter()
.map(|field| {
persist_column(
&field.column.source.to_string(),
&field.column.source.to_string(),
field.column.ty.clone(),
)
})
.collect();
model.persist = Some(Persist {
backends: vec![stored(&record, DatabaseKind::Sqlite, columns)],
table: None,
});
model
}
pub(crate) fn gathered() -> RecordModel {
let mut model = whole_row();
label(
&mut model,
"chapters",
Marker::Framework(FrameworkMarker {
label: Label::List,
element: None,
}),
);
let Some(persist) = model.persist.as_mut() else {
panic!("the model stores its columns")
};
let columns = &mut storage_of(&mut persist.backends[0]).columns;
let at = columns
.iter()
.position(|column| column.source == ident("chapters"))
.expect("the collection column is stored");
columns[at].stored = Some(ty("Uuid7"));
columns[at].from = Conversion::Infallible(path("path::to::store"));
model
}
pub(crate) fn gathered_in_mysql() -> RecordModel {
let mut model = gathered();
let record = model.record.clone();
let Some(persist) = model.persist.as_mut() else {
panic!("the model stores its columns")
};
let columns = storage_of(&mut persist.backends[0]).columns.clone();
persist.backends = vec![stored(&record, DatabaseKind::Mysql, columns)];
model
}
pub(crate) fn gathered_in_postgres() -> RecordModel {
let mut model = gathered();
let record = model.record.clone();
let Some(persist) = model.persist.as_mut() else {
panic!("the model stores its columns")
};
let columns = storage_of(&mut persist.backends[0]).columns.clone();
persist.backends = vec![stored(&record, DatabaseKind::Postgres, columns)];
model
}
pub(crate) fn edge_declared_in_postgres() -> RecordModel {
let mut model = gathered_in_postgres();
let Some(persist) = model.persist.as_mut() else {
panic!("the model stores its columns")
};
let columns = &mut storage_of(&mut persist.backends[0]).columns;
let at = columns
.iter()
.position(|column| column.source == ident("chapters"))
.expect("the collection column is stored");
columns[at].edge = true;
model
}
fn composed() -> RecordModel {
let mut model = whole_row();
let Some(persist) = model.persist.as_mut() else {
panic!("the model stores its columns")
};
let columns = &mut storage_of(&mut persist.backends[0]).columns;
let at = columns
.iter()
.position(|column| column.source == ident("checksum"))
.expect("the composite column is stored");
columns[at].flatten = true;
model
}
fn conversions(file: &syn::File) -> Vec<(String, String)> {
trait_impls(file)
.into_iter()
.filter(|(_, trait_path)| {
let rendered = tight(trait_path);
rendered.contains("::From<") || rendered.contains("::TryFrom<")
})
.map(|(item, trait_path)| (tight(trait_path), impl_of(item)))
.collect()
}
fn field_attrs(item: &syn::ItemStruct) -> Vec<String> {
named(item)
.iter()
.flat_map(|field| field.attrs.iter().map(tight))
.collect()
}
fn from_row_impl<'a>(file: &'a syn::File, row: &str) -> &'a syn::ItemImpl {
trait_impls(file)
.into_iter()
.find(|(item, path)| impl_of(item) == row && tight(path).contains("FromRow"))
.map(|(item, _)| item)
.unwrap_or_else(|| panic!("`{row}` carries a `FromRow` impl"))
}
fn decoded(file: &syn::File, row: &str) -> Vec<(String, Option<String>)> {
methods(from_row_impl(file, row))
.into_iter()
.flat_map(|method| &method.block.stmts)
.filter_map(|statement| {
let syn::Stmt::Local(local) = statement else {
return None;
};
let syn::Pat::Type(annotated) = &local.pat else {
return None;
};
let syn::Pat::Ident(field) = &*annotated.pat else {
return None;
};
let read = tight(local.init.as_ref()?.expr.as_ref());
let name = read
.split("FieldName::new(\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.map(ToOwned::to_owned);
Some((field.ident.to_string(), name))
})
.collect()
}
fn binds(pairs: &[(&str, &str)]) -> Vec<(String, Option<String>)> {
pairs
.iter()
.map(|(field, column)| ((*field).to_owned(), Some((*column).to_owned())))
.collect()
}
fn rendered(item: &syn::ItemImpl) -> String {
let file = syn::parse2(item.to_token_stream()).expect("one item is a parsable file");
prettyplease::unparse(&file)
}
pub(crate) fn struct_named<'a>(file: &'a syn::File, name: &str) -> &'a syn::ItemStruct {
structs(file)
.into_iter()
.find(|item| item.ident == name)
.unwrap_or_else(|| panic!("`{name}` is emitted"))
}
pub(crate) fn enum_named<'a>(file: &'a syn::File, name: &str) -> &'a syn::ItemEnum {
file
.items
.iter()
.find_map(|item| match item {
syn::Item::Enum(item) if item.ident == name => Some(item),
_ => None,
})
.unwrap_or_else(|| panic!("`{name}` is emitted"))
}
#[test]
fn every_declared_database_gets_its_own_row_type() {
assert_eq!(
names(&emission(&persisted())),
[
"VideoTrackKey",
"VideoTrackLineage",
"VideoTrackSqlite",
"VideoTrackSqliteComparison",
"VideoTrackRecord",
"VideoTrackRecordComparison",
"VideoTrackMongo",
"VideoTrackMongoComparison"
],
"in declaration order, each row followed by the comparison that shares its declaration — a \
renamed row takes the name the model gives it, and its comparison follows that name rather \
than the record's"
);
}
#[test]
fn an_record_with_no_persist_emits_no_row() {
for model in [video_track(), video(), media()] {
assert!(model.persist.is_none());
assert_eq!(
names(&emission(&model)).len(),
model.lineage.iter().count() + 1
);
}
}
#[test]
fn each_family_carries_its_own_derives() {
let file = emission(&persisted());
for name in ["VideoTrackSqlite", "VideoTrackRecord"] {
let attrs: Vec<String> = struct_named(&file, name)
.attrs
.iter()
.filter(|attr| !attr.path().is_ident("doc"))
.map(tight)
.collect();
assert_eq!(
attrs,
["#[derive(::core::fmt::Debug,::core::clone::Clone)]"],
"{name}"
);
}
let attrs: Vec<String> = struct_named(&file, "VideoTrackMongo")
.attrs
.iter()
.filter(|attr| !attr.path().is_ident("doc"))
.map(tight)
.collect();
assert_eq!(
attrs,
[
"#[derive(::core::fmt::Debug,::core::clone::Clone,::ingraph::__private::serde::Serialize,::ingraph::__private::serde::Deserialize)]",
"#[serde(crate=\"::ingraph::__private::serde\")]"
]
);
}
#[test]
fn the_row_writes_its_own_equality() {
let file = emission(&persisted());
let written = trait_impls(&file)
.into_iter()
.filter(|(item, path)| {
impl_of(item) == "VideoTrackSqlite" && tight(path) == "::core::cmp::PartialEq"
})
.map(|(item, _)| tight(item))
.collect::<Vec<_>>();
assert_eq!(
written,
[concat!(
"#[automatically_derived]",
"impl::core::cmp::PartialEqforVideoTrackSqlite{",
"#[inline]",
"fneq(&self,__ingraph_other:&Self)->::core::primitive::bool{",
"<u64as::ingraph::__private::column::ColumnEq>::column_eq(",
"&self.bitrate,&__ingraph_other.bitrate)",
"&&<Option<Uuid7>as::ingraph::__private::column::ColumnEq>::column_eq(",
"&self.cover_id,&__ingraph_other.cover_id)",
"}}"
)],
"one `ColumnEq` per stored column, folded, and nothing else"
);
let paged = trait_impls(&emission(&composed()))
.into_iter()
.filter(|(item, path)| {
impl_of(item) == "MediaSqliteCursor" && tight(path) == "::core::cmp::PartialEq"
})
.map(|(item, _)| tight(item))
.collect::<Vec<_>>();
assert_eq!(paged.len(), 1, "the page boundary compares too: {paged:?}");
assert!(
paged[0].contains("::ingraph::__private::column::ColumnEq>::column_eq"),
"{}",
paged[0]
);
assert!(
paged[0].contains("#[allow(unreachable_patterns)]_=>false"),
"a slot carries WHICH column it was written from: {}",
paged[0]
);
}
#[test]
fn every_row_field_carries_its_external_name() {
let file = emission(&persisted());
assert_eq!(
fields(struct_named(&file, "VideoTrackSqlite")),
["bitrate", "cover_id"]
);
assert!(
field_attrs(struct_named(&file, "VideoTrackSqlite")).is_empty(),
"{:?}",
field_attrs(struct_named(&file, "VideoTrackSqlite"))
);
assert_eq!(
decoded(&file, "VideoTrackSqlite"),
binds(&[("bitrate", "bitrate"), ("cover_id", "cover_id")])
);
assert_eq!(
decoded(&file, "VideoTrackRecord"),
binds(&[("bit_rate_v2", "bit_rate_v2"), ("cover_id", "cover_id")]),
"a per-database rename reaches the read that fetches the column"
);
assert_eq!(
field_attrs(struct_named(&file, "VideoTrackMongo")),
[
"#[serde(rename=\"bitrate\",with=\"::ingraph::__private::query::mongo::via\")]",
"#[serde(rename=\"cover_id\",with=\"::ingraph::__private::query::mongo::via\")]"
],
"mongo has no dialect, and no parameter shaped like one — and every field crosses the via, \
which is ONE path for every column rather than one this emitter chose per type"
);
}
#[test]
fn a_sql_rows_decode_binds_every_field_once_in_declaration_order() {
for model in [persisted(), whole_row(), aliased(wired())] {
let file = emission(&model);
for database in model.persist.iter().flat_map(|persist| &persist.backends) {
if !database.kind().is_sql() {
continue;
}
let row = database.name().to_string();
let pairs = decoded(&file, &row);
assert_eq!(
pairs
.iter()
.map(|(field, _)| field.clone())
.collect::<Vec<_>>(),
fields(struct_named(&file, &row)),
"`{row}` decodes its fields in declaration order, each exactly once"
);
let mut columns: Vec<&String> = pairs
.iter()
.filter_map(|(_, column)| column.as_ref())
.collect();
assert_eq!(
columns.len(),
pairs.len(),
"`{row}` names every field it reads"
);
columns.sort();
let read = columns.len();
columns.dedup();
assert_eq!(columns.len(), read, "`{row}` reads no column twice");
}
}
}
#[test]
fn the_row_field_carries_the_stored_type() {
let file = emission(&persisted());
let types = |name: &str| -> Vec<String> {
named(struct_named(&file, name))
.iter()
.map(|field| tight(&field.ty))
.collect()
};
assert_eq!(types("VideoTrackSqlite"), ["u64", "Option<Uuid7>"]);
assert_eq!(types("VideoTrackRecord"), ["BeU64", "Option<Uuid7>"]);
}
#[test]
fn a_column_rust_cannot_spell_still_emits() {
let mut model = whole_row();
let database = storage_of(&mut model.persist.as_mut().expect("stored").backends[0]);
database.columns[0].name = RustSafeName::new("bit-rate", proc_macro2::Span::call_site());
database.columns[1].name = RustSafeName::new("type", proc_macro2::Span::call_site());
let file = emission(&model);
let row = struct_named(&file, "MediaSqlite");
assert_eq!(fields(row)[..2], ["bit_rate", "type_"]);
assert_eq!(
decoded(&file, "MediaSqlite")[..2],
binds(&[("bit_rate", "bit-rate"), ("type_", "type")])[..],
"the mangling is the FIELD's; the database still sees `bit-rate` and `type`"
);
assert!(
method_names(&file).contains(&"bit_rate_ref".to_owned()),
"and the accessor takes the Rust face"
);
}
#[test]
fn a_row_gets_accessors_and_neither_a_constructor_nor_mutators() {
let file = emission(&persisted());
assert_eq!(
methods_of(&file, "VideoTrackSqlite"),
["bitrate_ref", "cover_id_ref"]
);
assert_eq!(
methods_of(&file, "VideoTrackRecord"),
["bit_rate_v2", "bit_rate_v2_ref", "cover_id_ref"],
"`copy` in the database block adds the by-value accessor, exactly as the domain marker does"
);
}
#[test]
fn the_copy_claim_is_the_databases_not_the_domains() {
let file = emission(&persisted());
assert!(!methods_of(&file, "VideoTrackSqlite").contains(&"bitrate".to_owned()));
assert!(is_const(method_of(
&file,
"VideoTrackRecord",
"bit_rate_v2"
)));
}
#[test]
fn a_row_column_is_never_projected_through_a_framework_trait() {
let file = emission(&persisted());
assert_eq!(
returns(method_of(&file, "VideoTrackSqlite", "cover_id_ref")),
"&Option<Uuid7>",
"an `Option<_>` column is borrowed as itself — nullability is the schema's business"
);
}
#[test]
fn exactly_one_of_from_and_try_from_is_emitted_per_direction() {
let file = emission(&persisted());
let pairs = conversions(&file);
let of = |row: &str| -> Vec<String> {
pairs
.iter()
.filter(|(trait_path, target)| target == row || trait_path.contains(&format!("<{row}>")))
.map(|(trait_path, target)| format!("{trait_path} for {target}"))
.collect()
};
assert_eq!(
of("VideoTrackSqlite"),
["::core::convert::From<VideoTrack> for VideoTrackSqlite"],
"nothing is fallible, and the row is partial — so one direction, infallible"
);
assert_eq!(
of("VideoTrackRecord"),
["::core::convert::From<VideoTrack> for VideoTrackRecord"],
"the fallible one here is `into` — which by the VERB RULE LEAVES the row, so it is the read — \
and the read is not emitted for a partial row. What is left is the infallible write. \
Fallibility is decided per DIRECTION."
);
let mut fallible_write = persisted();
storage_of(&mut fallible_write.persist.as_mut().expect("stored").backends[0]).columns[0].from =
fallible(path("narrow"));
assert!(
conversions(&emission(&fallible_write))
.iter()
.any(
|(trait_path, target)| trait_path == "::core::convert::TryFrom<VideoTrack>"
&& target == "VideoTrackSqlite"
),
"and one fallible column in the direction being emitted makes that whole direction fallible"
);
for (trait_path, target) in &pairs {
let both = pairs
.iter()
.filter(|(other, other_target)| {
other_target == target
&& other.replace("TryFrom", "From") == trait_path.replace("TryFrom", "From")
})
.count();
assert_eq!(both, 1, "`{trait_path}` for `{target}` is emitted once");
}
}
#[test]
fn the_reverse_conversion_needs_a_whole_row_or_a_container_conversion() {
assert_eq!(
conversions(&emission(&persisted()))
.iter()
.filter(|(_, target)| target == "VideoTrack")
.count(),
0,
"a partial row cannot rebuild the record it does not carry"
);
let file = emission(&whole_row());
assert_eq!(
conversions(&file)
.into_iter()
.filter(|(trait_path, target)| trait_path.contains("MediaSqlite") || target == "MediaSqlite")
.collect::<Vec<_>>(),
[
(
"::core::convert::From<Media>".to_owned(),
"MediaSqlite".to_owned()
),
(
"::core::convert::From<MediaSqlite>".to_owned(),
"Media".to_owned()
),
],
"a total row goes both ways"
);
let mut declared = persisted();
storage_of(&mut declared.persist.as_mut().expect("stored").backends[0]).into =
Conversion::Infallible(path("rebuild"));
assert!(
conversions(&emission(&declared))
.iter()
.any(
|(trait_path, target)| trait_path.contains("From<VideoTrackSqlite>")
&& target == "VideoTrack"
),
"the container conversion is the seam for supplying what a partial row is missing"
);
}
#[test]
fn each_column_is_converted_the_way_the_declaration_says() {
let body = |file: &syn::File, name: &str| -> String {
trait_impls(file)
.into_iter()
.find(|(item, _)| impl_of(item) == name)
.map(|(item, _)| tight(item))
.unwrap_or_else(|| panic!("`{name}` has a conversion"))
};
let file = emission(&persisted());
assert!(
body(&file, "VideoTrackRecord").contains("bit_rate_v2:path::to::store(record.checksum)"),
"{}",
body(&file, "VideoTrackRecord")
);
assert!(
body(&file, "VideoTrackSqlite").contains("bitrate:record.checksum"),
"no override and no conversion — the value is moved, with no reflexive `Into` in the way"
);
let mut converted = whole_row();
storage_of(&mut converted.persist.as_mut().expect("stored").backends[0]).columns[0].stored =
Some(ty("BeU64"));
assert!(
body(&emission(&converted), "MediaSqlite")
.contains("id:::core::convert::Into::into(record.id)"),
"a `type` override with no declared conversion goes through `Into`"
);
}
#[test]
fn a_fallible_conversion_uses_the_question_mark_and_a_boxed_error() {
let mut model = whole_row();
storage_of(&mut model.persist.as_mut().expect("stored").backends[0]).columns[0].into =
fallible(path("check"));
let file = emission(&model);
let raise = trait_impls(&file)
.into_iter()
.find(|(item, path)| impl_of(item) == "Media" && tight(path).contains("TryFrom"))
.map(|(item, _)| tight(item))
.expect("the fallible read is a `TryFrom`");
assert!(raise.contains("id:check(row.id)?"), "{raise}");
assert!(
raise.contains(
"typeError=::std::boxed::Box<dyn::core::error::Error+::core::marker::Send+::core::marker::Sync+'static>"
),
"{raise}"
);
}
#[test]
fn a_declared_cell_types_its_own_crossing_and_reaches_no_other() {
let mut model = ordered();
{
let sqlite = storage_of(&mut model.persist.as_mut().expect("stored").backends[0]);
sqlite.columns[3].from = fallible(path("store"));
sqlite.columns[3].into = fallible(path("check"));
}
model.errors = vec![
crate::model::BackendError {
crossing: crate::model::Crossing::PersistWrite,
kind: DatabaseKind::Sqlite,
path: path("crate::StoreRefusal"),
},
crate::model::BackendError {
crossing: crate::model::Crossing::PersistRead,
kind: DatabaseKind::Sqlite,
path: path("crate::RowRefusal"),
},
crate::model::BackendError {
crossing: crate::model::Crossing::Output,
kind: DatabaseKind::Sqlite,
path: path("crate::WireRefusal"),
},
];
let file = emission(&model);
let crossing = |self_type: &str| {
trait_impls(&file)
.into_iter()
.find(|(item, path)| impl_of(item) == self_type && tight(path).contains("TryFrom"))
.map(|(item, _)| tight(item))
.unwrap_or_else(|| panic!("`{self_type}` is the target of a fallible crossing"))
};
let store = crossing("VideoTrackSqlite");
assert!(
store.contains("typeError=crate::StoreRefusal"),
"the WRITE leg's cell types the impl the write lane crosses through: {store}"
);
assert!(
!store.contains("RowRefusal") && !store.contains("WireRefusal"),
"and neither of the other two reaches it: {store}"
);
let onto_wire = crossing("VideoTrackGraphqlOutput");
assert!(
onto_wire.contains("typeError=crate::WireRefusal"),
"the crossing onto the wire answers with its own, which is what a per-leg cell is for: \
{onto_wire}"
);
}
#[test]
fn the_schema_binding_is_on_the_record_once_per_describable_database() {
let model = queried();
let file = emission(&model);
let described: Vec<String> = trait_impls(&file)
.into_iter()
.filter(|(_, path)| tight(path).contains("schema::Describe"))
.map(|(item, path)| format!("{} for {}", tight(path), impl_of(item)))
.collect();
let backends: Vec<String> = model
.describable()
.into_iter()
.map(|database| tight(database.backend_type(&model)))
.collect();
assert_eq!(
described.len(),
backends.len(),
"one blueprint per describable database: {described:?}"
);
assert!(!backends.is_empty(), "`queried` describes at least one");
for backend in &backends {
assert!(
described
.iter()
.any(|row| row.contains(backend) && row.ends_with(&format!(" for {}", model.record))),
"the blueprint for {backend} is on the record: {described:?}"
);
}
assert!(
unauthorised_framework_impls(&model, &file)
.iter()
.all(|row| !row.contains("schema::Describe")),
"and every one of them is authorised"
);
}
#[test]
fn the_rows_declare_no_framework_trait_impl() {
const QUERY_BINDINGS: [&str; 3] = [
"query::sql::SqlQuery",
"query::sql::SqlOrdering",
"query::sql::SqlWrite",
];
for model in [persisted(), whole_row()] {
let file = emission(&model);
let rows: Vec<String> = model
.persist
.iter()
.flat_map(|persist| &persist.backends)
.map(|database| database.name().to_string())
.collect();
let framework: Vec<String> = trait_impls(&file)
.into_iter()
.filter(|(item, _)| rows.contains(&impl_of(item)))
.filter(|(_, path)| framework_rooted(path, &model.krate))
.map(|(_, path)| tight(path))
.filter(|path| !QUERY_BINDINGS.iter().any(|binding| path.contains(binding)))
.collect();
assert!(framework.is_empty(), "{framework:?}");
assert!(
framework_paths_not_through_a_private_module(&model).is_empty(),
"and every framework path still goes through `__private`"
);
}
}
#[test]
fn the_query_binding_declares_the_record_and_the_address_alone() {
let file = emission(&whole_row());
let slots: Vec<Vec<String>> = trait_impls(&file)
.into_iter()
.filter(|(_, path)| tight(path).contains("query::sql::SqlQuery"))
.map(|(item, _)| {
item
.items
.iter()
.filter_map(|item| match item {
syn::ImplItem::Type(bound) => Some(bound.ident.to_string()),
_ => None,
})
.collect()
})
.collect();
assert_eq!(
slots,
[["Record".to_owned(), "Address".to_owned()]],
"one binding per SQL database, naming the record and the address and nothing else"
);
}
#[test]
fn the_page_binding_names_its_subjects_and_reads_the_decoded_row() {
let file = emission(&whole_row());
let bindings: Vec<(Vec<String>, usize)> = trait_impls(&file)
.into_iter()
.filter(|(_, path)| tight(path).contains("query::sql::SqlOrdering"))
.map(|(item, _)| {
let slots = item
.items
.iter()
.filter_map(|item| match item {
syn::ImplItem::Type(bound) => Some(bound.ident.to_string()),
_ => None,
})
.collect();
let arity = item
.items
.iter()
.find_map(|item| match item {
syn::ImplItem::Fn(method) if method.sig.ident == "value" => Some(method.sig.inputs.len()),
_ => None,
})
.expect("the page binding projects the row into cursor values");
(slots, arity)
})
.collect();
assert_eq!(
bindings,
[(
vec![
"Order".to_owned(),
"Value".to_owned(),
"Subjects".to_owned()
],
5
)],
"one page binding per SQL database, naming three slots and reading the row at five"
);
}
fn nested_whole_row() -> RecordModel {
let mut model = model("VideoTrack", &["media_id", "video_id"], "id");
let record = model.record.clone();
let columns: Vec<PersistColumn> = model
.fields
.iter()
.map(|field| {
persist_column(
&field.column.source.to_string(),
&field.column.source.to_string(),
field.column.ty.clone(),
)
})
.collect();
let sqlite = stored(&record, DatabaseKind::Sqlite, columns.clone());
let mut postgres = stored(&record, DatabaseKind::Postgres, columns);
let storage = storage_of(&mut postgres);
storage.name = ident("VideoTrackRecord");
storage.comparison = default_comparison_name(&ident("VideoTrackRecord"));
storage.columns[2].name = RustSafeName::new("pk", proc_macro2::Span::call_site());
model.persist = Some(Persist {
backends: vec![sqlite, postgres],
table: Some(RustSafeName::new(
"video_tracks",
proc_macro2::Span::call_site(),
)),
});
model
}
#[test]
fn the_address_is_the_id_column_alone() {
let file = emission(&nested_whole_row());
let field_name = "::ingraph::__private::field::FieldName";
let record_address = "::ingraph::__private::comparison::RecordAddress";
let key_in = "::ingraph::__private::comparison::sql::SqlKeyIn";
let identifiable = "::ingraph::__private::transform::Identifiable";
let crossing = "::ingraph::__private::query::sql::CrossingError";
let db = database_parameter();
let bound = |item: &syn::ItemImpl, name: &str| {
item
.items
.iter()
.find_map(|item| match item {
syn::ImplItem::Const(item) if item.ident == name => Some(tight(&item.expr)),
syn::ImplItem::Type(item) if item.ident == name => Some(tight(&item.ty)),
syn::ImplItem::Fn(item) if item.sig.ident == name => Some(tight(&item.block)),
_ => None,
})
.unwrap_or_else(|| panic!("every binding states its `{name}`"))
};
let signature = |item: &syn::ItemImpl| {
item
.items
.iter()
.find_map(|item| match item {
syn::ImplItem::Fn(item) if item.sig.ident == "addresses" => Some(tight(&item.sig)),
_ => None,
})
.expect("every binding states its `addresses`")
};
let bindings: Vec<(String, String, String, String, String)> = trait_impls(&file)
.into_iter()
.filter(|(_, path)| tight(path).contains("query::sql::SqlQuery"))
.map(|(item, _)| {
(
impl_of(item),
bound(item, "ADDRESS"),
bound(item, "Address"),
signature(item),
bound(item, "addresses"),
)
})
.collect();
let expected = [
("VideoTrackSqlite", "VideoTrackSqliteCursor", "id"),
("VideoTrackRecord", "VideoTrackRecordCursor", "pk"),
];
assert_eq!(
bindings.len(),
expected.len(),
"one binding per SQL database: {bindings:?}"
);
for ((row, address, slot, takes, body), (name, cursor, column)) in bindings.iter().zip(expected) {
assert_eq!(row, name, "the rows are walked in declaration order");
assert_eq!(
address,
&format!(
"{record_address}::new({field_name}::new(\"video_tracks\"),\
&[{field_name}::new(\"{column}\")],)"
),
"the address is the table and ONE column"
);
assert_eq!(
slot,
&format!("{key_in}<{cursor},{db},1>"),
"the general row-value `IN` at width one, not a second scalar machine"
);
assert_eq!(
takes,
&format!(
"fn addresses(ids: &[<VideoTrack as {identifiable}>::Id],) \
-> ::core::result::Result<Self::Address, {crossing}>"
)
.replace(' ', ""),
"the engine face is handed a SLICE of ids, qualified through the trait that OWNS one — one \
predicate at every width, so `get` and an interface's id-gather lane render alike"
);
assert_eq!(
body,
&format!(
"{{let mut __ingraph_keys=::std::vec::Vec::with_capacity(<[_]>::len(ids));\
for __ingraph_id in ids{{::std::vec::Vec::push(&mut __ingraph_keys,\
[{cursor}::Id(::core::clone::Clone::clone(__ingraph_id))]);}}\
::core::result::Result::Ok({key_in}::new([\"{column}\"],__ingraph_keys))}}"
)
.replace(' ', ""),
"one part, one slot per id, and the value read off each id the caller spent"
);
}
let selected = plan_of(&file, "VideoTrackSqlite", "COLUMNS").expect("a stored row selects");
let column_name = "::ingraph::__private::column::ColumnName";
for column in ["media_id", "video_id"] {
assert!(
selected.contains(&format!("{column_name}::new(\"{column}\")")),
"`{column}` is still a stored column of the row: {selected}"
);
}
}
fn plan_of(file: &syn::File, row: &str, name: &str) -> Option<String> {
trait_impls(file)
.into_iter()
.find(|(item, path)| impl_of(item) == row && tight(path).contains("query::sql::SqlQuery"))
.and_then(|(item, _)| {
item.items.iter().find_map(|item| match item {
syn::ImplItem::Const(item) if item.ident == name => Some(tight(&item.expr)),
_ => None,
})
})
}
#[test]
fn a_gathered_collection_leaves_the_select_list_for_the_plan() {
let file = emission(&gathered());
let shelf = "::ingraph::__private";
assert_eq!(
plan_of(&file, "MediaSqlite", "COLUMNS").expect("the query binding states its columns"),
format!(
"&[{shelf}::column::shape::<Uuid7>({shelf}::column::ColumnName::new(\"id\")),\
{shelf}::column::shape::<u64>({shelf}::column::ColumnName::new(\"checksum\")),\
{shelf}::column::shape::<Option<Uuid7>>({shelf}::column::ColumnName::new(\"cover_id\")),]"
),
"`chapters` is not among them — it names no column of `media`"
);
assert_eq!(
plan_of(&file, "MediaSqlite", "COLLECTIONS").expect("and states its plan"),
format!(
"&[{shelf}::query::sql::EdgeCollection::gather(\
&[{shelf}::field::FieldName::new(\"chapters\")],\
{shelf}::query::sql::EdgeShape::Sequence,\
__ingraph_key_sqlite::<__INGRAPH_DB__>,\
__ingraph_take_sqlite_chapters::<__INGRAPH_DB__>,),]"
),
"one entry, carrying the column's path, its shape and the two typed crossings"
);
assert_eq!(
plan_of(&emission(&whole_row()), "MediaSqlite", "COLLECTIONS"),
None,
"the same model without the word states no plan at all"
);
}
#[test]
fn each_database_mints_its_aliases_in_its_own_namespace() {
let mut model = whole_row();
let record = model.record.clone();
let persist = model.persist.as_mut().expect("the whole row is stored");
let columns = storage_of(&mut persist.backends[0]).columns.clone();
persist
.backends
.push(stored(&record, DatabaseKind::Postgres, columns));
storage_of(&mut persist.backends[0]).aliases = AliasOptions {
prefix: Some("__mine".to_owned()),
depth: Some(16),
};
let file = emission(&model);
let sqlite = plan_of(&file, "MediaSqlite", "ALIASES").expect("the row states its aliases");
assert!(
sqlite.starts_with("&[\"__mine_media_0__\",\"__mine_media_1__\","),
"{sqlite}"
);
assert!(sqlite.ends_with("\"__mine_media_15__\"]"), "{sqlite}");
assert_eq!(
plan_of(&file, "MediaPostgres", "ALIASES").expect("and so does the one beside it"),
"&[\"__ig_media_0__\",\"__ig_media_1__\",\"__ig_media_2__\",\"__ig_media_3__\",\
\"__ig_media_4__\",\"__ig_media_5__\",\"__ig_media_6__\",\"__ig_media_7__\"]",
"the database that named nothing keeps the framework's own answers"
);
}
#[test]
fn the_edge_word_moves_a_postgres_collection_off_the_row() {
let shelf = "::ingraph::__private";
let wordless = emission(&gathered_in_postgres());
assert_eq!(
plan_of(&wordless, "MediaPostgres", "COLUMNS").expect("the query binding states its columns"),
format!(
"&[{shelf}::column::shape::<Uuid7>({shelf}::column::ColumnName::new(\"id\")),\
{shelf}::column::shape::<u64>({shelf}::column::ColumnName::new(\"checksum\")),\
{shelf}::column::shape::<::std::vec::Vec<Uuid7>>(\
{shelf}::column::ColumnName::new(\"chapters\")),\
{shelf}::column::shape::<Option<Uuid7>>({shelf}::column::ColumnName::new(\"cover_id\")),]"
),
"with no word the collection is a column of the row, and the array is what the row decodes"
);
assert_eq!(
plan_of(&wordless, "MediaPostgres", "COLLECTIONS"),
None,
"and there is no plan at all — the engine's default const is the whole of it"
);
let worded = emission(&edge_declared_in_postgres());
assert_eq!(
plan_of(&worded, "MediaPostgres", "COLUMNS").expect("the query binding states its columns"),
format!(
"&[{shelf}::column::shape::<Uuid7>({shelf}::column::ColumnName::new(\"id\")),\
{shelf}::column::shape::<u64>({shelf}::column::ColumnName::new(\"checksum\")),\
{shelf}::column::shape::<Option<Uuid7>>({shelf}::column::ColumnName::new(\"cover_id\")),]"
),
"the word takes it out of the SELECT list, exactly as a gathered column leaves one"
);
assert_eq!(
plan_of(&worded, "MediaPostgres", "COLLECTIONS").expect("and states its plan"),
format!(
"&[{shelf}::query::sql::EdgeCollection::aggregate(\
&[{shelf}::field::FieldName::new(\"chapters\")],\
{shelf}::query::sql::EdgeShape::Sequence,\
__ingraph_take_postgres_chapters::<__INGRAPH_DB__>,),]"
),
"an AGGREGATE entry, and no key binder beside it"
);
assert!(
!tight(&worded).contains("__ingraph_key_postgres"),
"the binder is not emitted at all where nothing gathers: {}",
tight(&worded)
);
}
#[test]
fn the_other_gathering_dialect_states_the_same_plan_under_its_own_names() {
let file = emission(&gathered_in_mysql());
let shelf = "::ingraph::__private";
assert_eq!(
plan_of(&file, "MediaMysql", "COLUMNS").expect("the query binding states its columns"),
format!(
"&[{shelf}::column::shape::<Uuid7>({shelf}::column::ColumnName::new(\"id\")),\
{shelf}::column::shape::<u64>({shelf}::column::ColumnName::new(\"checksum\")),\
{shelf}::column::shape::<Option<Uuid7>>({shelf}::column::ColumnName::new(\"cover_id\")),]"
),
"`chapters` names no column of `media` here either"
);
assert_eq!(
plan_of(&file, "MediaMysql", "COLLECTIONS").expect("and states its plan"),
format!(
"&[{shelf}::query::sql::EdgeCollection::gather(\
&[{shelf}::field::FieldName::new(\"chapters\")],\
{shelf}::query::sql::EdgeShape::Sequence,\
__ingraph_key_mysql::<__INGRAPH_DB__>,\
__ingraph_take_mysql_chapters::<__INGRAPH_DB__>,),]"
),
"the same entry, under the crossings this DATABASE names"
);
}
#[test]
fn the_order_by_is_emitted_for_a_stored_record_with_no_wire_face() {
assert!(
whole_row().graphql.is_none(),
"the fixture has no wire face"
);
assert!(
declared_types(&emission(&whole_row())).contains(&"MediaOrderBy".to_owned()),
"a record with no `graphql(…)` still gets its ordering term"
);
assert!(
!declared_types(&emission(&video_track())).contains(&"VideoTrackOrderBy".to_owned()),
"a record stored nowhere has no stored column to order by"
);
let wired = wired();
let types = declared_types(&emission(&wired));
assert_eq!(
types
.iter()
.filter(|name| *name == "VideoTrackOrderBy")
.count(),
1,
"exactly once for a record that does declare a wire face: {types:?}"
);
let (wire_types, _) = wired
.graphql
.as_ref()
.expect("the fixture declares a wire face")
.faces(&wired);
let wire: syn::File = syn::parse2(wire_types).expect("the wire face is parsable");
assert!(
!declared_types(&wire).contains(&"VideoTrackOrderBy".to_owned()),
"and the WIRE FACE is no longer what declares it: {:?}",
declared_types(&wire)
);
}
#[test]
fn the_rows_are_structs_outside_the_const_and_impls_inside() {
let file = emission(&persisted());
assert_eq!(
file
.items
.iter()
.filter(|item| matches!(item, syn::Item::Const(anonymous) if anonymous.ident == "_"))
.count(),
1
);
assert!(
!file
.items
.iter()
.any(|item| matches!(item, syn::Item::Impl(_))),
"no impl at top level"
);
assert_eq!(
structs(&file).len(),
8,
"the key, the lineage, and three rows each with its comparison"
);
}
#[test]
fn the_rows_are_documented_and_inline() {
const NOT_WRAPPERS: &[&str] = &["from_row", "from_document", "apply"];
let file = emission(&persisted());
for name in ["VideoTrackSqlite", "VideoTrackRecord", "VideoTrackMongo"] {
assert!(documented(&struct_named(&file, name).attrs), "{name}");
}
for method in impls(&file).iter().flat_map(|item| methods(item)) {
if NOT_WRAPPERS.contains(&method.sig.ident.to_string().as_str()) {
continue;
}
assert!(
method.attrs.iter().any(|attr| tight(attr) == "#[inline]"),
"`{}`",
method.sig.ident
);
}
}
#[test]
fn the_emitted_decode_is_the_shape_sqlxs_derive_would_have_written() {
assert_eq!(
rendered(from_row_impl(&emission(&whole_row()), "MediaSqlite")),
MEDIA_SQLITE_DECODE
);
}
const MEDIA_SQLITE_DECODE: &str = "\
#[automatically_derived]
impl<
'a,
__INGRAPH_ROW__: ::ingraph::__private::sqlx::Row,
> ::ingraph::__private::sqlx::FromRow<'a, __INGRAPH_ROW__> for MediaSqlite
where
Uuid7: ::ingraph::__private::column::Assemble<'a, __INGRAPH_ROW__>,
u64: ::ingraph::__private::column::Assemble<'a, __INGRAPH_ROW__>,
Vec<Uuid7>: ::ingraph::__private::column::Assemble<'a, __INGRAPH_ROW__>,
Option<Uuid7>: ::ingraph::__private::column::Assemble<'a, __INGRAPH_ROW__>,
{
/// Read a [`MediaSqlite`] back out of a database row, each field under its own name — and a field whose type spans several columns out of every one of them.
fn from_row(__row: &'a __INGRAPH_ROW__) -> ::ingraph::__private::sqlx::Result<Self> {
let id: Uuid7 = ::ingraph::__private::column::assembled(
__row,
::ingraph::__private::field::FieldName::new(\"id\"),
::core::option::Option::None,
)?;
let checksum: u64 = ::ingraph::__private::column::assembled(
__row,
::ingraph::__private::field::FieldName::new(\"checksum\"),
::core::option::Option::None,
)?;
let chapters: Vec<Uuid7> = ::ingraph::__private::column::assembled(
__row,
::ingraph::__private::field::FieldName::new(\"chapters\"),
::core::option::Option::None,
)?;
let cover_id: Option<Uuid7> = ::ingraph::__private::column::assembled(
__row,
::ingraph::__private::field::FieldName::new(\"cover_id\"),
::core::option::Option::None,
)?;
::core::result::Result::Ok(Self {
id,
checksum,
chapters,
cover_id,
})
}
}
";
#[test]
fn every_sqlx_name_goes_through_the_shelf() {
for mut model in [persisted(), whole_row(), aliased(wired())] {
for krate in [
syn::parse_quote!(::ingraph),
syn::parse_quote!(shim::vendored::ingraph),
] {
model.krate = krate;
let unshelved = sqlx_names_outside_the_shelf(&model);
assert!(
unshelved.is_empty(),
"`{}` reaches sqlx outside `__private::sqlx`: {unshelved:?}",
model.record
);
}
}
}
fn sqlx_names_outside_the_shelf(model: &RecordModel) -> Vec<String> {
fn flatten(stream: proc_macro2::TokenStream, into: &mut Vec<proc_macro2::TokenTree>) {
for tree in stream {
match tree {
proc_macro2::TokenTree::Group(group) => flatten(group.stream(), into),
other => into.push(other),
}
}
}
let mut tokens = Vec::new();
flatten(model.emit(), &mut tokens);
let colon = |at: usize| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ':');
let shelved = |at: usize| {
at >= 3
&& colon(at - 1)
&& colon(at - 2)
&& matches!(tokens.get(at - 3), Some(proc_macro2::TokenTree::Ident(id)) if id == "__private")
};
(0..tokens.len())
.filter(|at| matches!(tokens.get(*at), Some(proc_macro2::TokenTree::Ident(id)) if id == "sqlx"))
.filter(|at| !shelved(*at))
.map(|at| {
tokens[at.saturating_sub(3)..(at + 3).min(tokens.len())]
.iter()
.map(ToString::to_string)
.collect()
})
.collect()
}
#[test]
fn the_rows_mirror_the_records_visibility() {
for (model, expected) in [(persisted(), "pub"), (private(persisted()), "")] {
let file = emission(&model);
for name in ["VideoTrackSqlite", "VideoTrackRecord", "VideoTrackMongo"] {
let item = struct_named(&file, name);
assert_eq!(tight(&item.vis), expected, "{name}");
for field in named(item) {
assert_eq!(tight(&field.vis), "", "{name}");
}
}
}
}
#[test]
fn no_row_is_generic_over_a_dialect() {
let model = persisted();
let file = emission(&model);
for database in model.persist.iter().flat_map(|persist| &persist.backends) {
let item = struct_named(&file, &database.name().to_string());
assert!(
item.generics.params.is_empty() && item.generics.where_clause.is_none(),
"`{}` carries a parameter",
item.ident
);
}
}
#[test]
fn the_comparison_is_the_only_generic_emitted_type() {
let model = persisted();
let file = emission(&model);
let comparisons: Vec<String> = model
.persist
.iter()
.flat_map(|persist| &persist.backends)
.map(|database| database.comparison_name().to_string())
.collect();
for item in structs(&file) {
let parameters: Vec<String> = item.generics.params.iter().map(tight).collect();
if comparisons.contains(&item.ident.to_string()) {
assert_eq!(parameters, [database_parameter()], "`{}`", item.ident);
assert!(
tight(&item.generics.where_clause).contains(&format!(
"{}:::ingraph::__private::comparison::Backend",
database_parameter()
)),
"`{}` is generic over a database and does not say it IS one, so a `where F: \
ToDatabaseComparison<V, Db>` beside it is not well formed",
item.ident
);
} else {
assert!(parameters.is_empty(), "`{}`: {parameters:?}", item.ident);
}
}
}
#[test]
fn every_generic_parameter_the_emission_introduces_is_namespaced() {
let file = emission(&wired());
let declared = structs(&file)
.into_iter()
.map(|item| (item.ident.to_string(), &item.generics))
.chain(
impls(&file)
.into_iter()
.map(|item| (impl_of(item), &item.generics)),
);
for (subject, generics) in declared {
for parameter in &generics.params {
let syn::GenericParam::Type(parameter) = parameter else {
continue;
};
let name = parameter.ident.to_string();
assert!(
name.starts_with("__") && name.ends_with("__"),
"`{name}` on `{subject}` is a bare parameter, and shadows a declaration's own type of that \
name"
);
}
}
}
fn whole_document() -> RecordModel {
let mut model = whole_row();
let columns = model.persist.as_ref().expect("stored").backends[0]
.columns()
.to_vec();
model.persist.as_mut().expect("stored").backends =
vec![stored(&ident("Media"), DatabaseKind::Mongo, columns)];
model
}
#[test]
fn the_mongo_document_names_nothing_of_the_sql_family() {
let model = whole_document();
let file = emission(&model);
let document = struct_named(&file, "MediaMongo");
let rendered = tight(document);
assert!(
rendered.contains("::ingraph::__private::serde::Serialize"),
"{rendered}"
);
assert!(
rendered.contains("::ingraph::__private::serde::Deserialize"),
"{rendered}"
);
let whole = tight(model.emit());
assert!(!whole.contains("sqlx"), "{whole}");
assert!(!whole.contains("FromRow"), "{whole}");
assert!(
field_attrs(document)
.iter()
.all(|attr| attr.starts_with("#[serde(rename=")),
"{:?}",
field_attrs(document)
);
}
#[test]
fn the_mongo_document_reads_every_column_through_one_extraction() {
let file = emission(&whole_document());
let extraction = tight(
all_items(&file)
.into_iter()
.filter_map(|item| match item {
syn::Item::Impl(item) => Some(item),
_ => None,
})
.flat_map(methods)
.find(|method| method.sig.ident == "from_document")
.expect("the document carries its extraction"),
);
let field = "::ingraph::__private::query::mongo::field";
let signature =
"pub fn from_document(__ingraph_document: &::ingraph::__private::bson::Document,) \
-> ::core::result::Result<Self, \
::ingraph::__private::query::mongo::MongoExtractionError>"
.replace(' ', "");
assert!(extraction.contains(&signature), "{extraction}");
for (column, ty, key) in [
("id", "Uuid7", "_id"),
("checksum", "u64", "checksum"),
("chapters", "Vec<Uuid7>", "chapters"),
("cover_id", "Option<Uuid7>", "cover_id"),
] {
assert!(
extraction.contains(&format!(
"{column}:{field}::<{ty}>(__ingraph_document,\"{key}\")?"
)),
"`{column}` in {extraction}"
);
}
}
#[test]
fn a_sql_rows_flatten_leaves_the_documents_extraction_alone() {
let model = flattened_document();
let file = emission(&model);
let extractions = all_items(&file)
.into_iter()
.filter_map(|item| match item {
syn::Item::Impl(item) => Some(item),
_ => None,
})
.flat_map(methods)
.filter(|method| method.sig.ident == "from_document")
.count();
assert_eq!(extractions, 1, "the document reads itself back");
assert!(
model
.emitted_methods()
.iter()
.any(|method| method.name == "from_document"),
"and the enumeration claims the name the emission declares"
);
assert!(
!field_attrs(struct_named(&file, "MediaMongo"))
.iter()
.any(|attr| attr == "#[serde(flatten)]"),
"and no field of the document is flattened: {:?}",
field_attrs(struct_named(&file, "MediaMongo"))
);
let mut marked = whole_document();
for database in marked
.persist
.iter_mut()
.flat_map(|persist| &mut persist.backends)
.filter(|database| !database.kind().is_sql())
{
storage_of(database).columns[0].flatten = true;
}
assert!(
marked
.emitted_methods()
.iter()
.any(|method| method.name == "from_document"),
"a document extracts because it is a document, not because of what its columns carry"
);
}
fn flattened_document() -> RecordModel {
let mut model = whole_document();
flatten_the_first_sql_column(&mut model);
model
}
fn flatten_the_first_sql_column(model: &mut RecordModel) {
for database in model
.persist
.iter_mut()
.flat_map(|persist| &mut persist.backends)
.filter(|database| database.kind().is_sql())
{
storage_of(database).columns[0].flatten = true;
}
}
#[test]
fn the_mongo_document_reads_the_id_out_of_underscore_id() {
let file = emission(&whole_document());
let document = struct_named(&file, "MediaMongo");
assert_eq!(
field_attrs(document),
[
"#[serde(rename=\"_id\",with=\"::ingraph::__private::query::mongo::via\")]",
"#[serde(rename=\"checksum\",with=\"::ingraph::__private::query::mongo::via\")]",
"#[serde(rename=\"chapters\",with=\"::ingraph::__private::query::mongo::via\")]",
"#[serde(rename=\"cover_id\",with=\"::ingraph::__private::query::mongo::via\")]",
]
);
let without = emission(&persisted());
assert_eq!(
field_attrs(struct_named(&without, "VideoTrackMongo")),
[
"#[serde(rename=\"bitrate\",with=\"::ingraph::__private::query::mongo::via\")]",
"#[serde(rename=\"cover_id\",with=\"::ingraph::__private::query::mongo::via\")]"
]
);
assert!(field_attrs(struct_named(&without, "VideoTrackSqlite")).is_empty());
}
#[test]
fn the_mongo_document_reaches_serde_through_the_shelf() {
for (krate, shelf) in [
(syn::parse_quote!(::ingraph), "::ingraph::__private::serde"),
(
syn::parse_quote!(shim::vendored::ingraph),
"shim::vendored::ingraph::__private::serde",
),
] {
let mut model = whole_document();
model.krate = krate;
let file = emission(&model);
let attrs: Vec<String> = struct_named(&file, "MediaMongo")
.attrs
.iter()
.filter(|attr| !attr.path().is_ident("doc"))
.map(tight)
.collect();
assert_eq!(
attrs,
[
format!(
"#[derive(::core::fmt::Debug,::core::clone::Clone,{shelf}::Serialize,{shelf}::Deserialize)]"
),
format!("#[serde(crate=\"{shelf}\")]")
]
);
let via = format!("{}::query::mongo::via", shelf.trim_end_matches("::serde"));
for attr in field_attrs(struct_named(&file, "MediaMongo")) {
assert!(
attr.contains(&format!("with=\"{via}\"")),
"every field crosses the via, at the declarer's own crate path: {attr}"
);
}
}
}
use crate::model::{
AsyncGraphql, Face, FrameworkMarker, Graphql, GraphqlBackend, GraphqlField, Label, Marker,
WirePosition, default_comparison_name, default_filter_name, default_input_name,
default_key_output_name, default_order_by_name, default_output_name,
};
pub(crate) fn wired() -> RecordModel {
let mut model = persisted();
let base = model.record.clone();
let face = |sdl: &str, attrs: proc_macro2::TokenStream| Face {
name: RustSafeName::new(sdl, proc_macro2::Span::call_site()),
attrs,
};
let field = |source: &str, sdl: &str, ty: syn::Type| GraphqlField {
source: ident(source),
domain: ty,
wire: None,
output_crossing: WirePosition::default(),
input_crossing: WirePosition::default(),
input: face(sdl, proc_macro2::TokenStream::new()),
output: face(sdl, quote::quote!(desc = "bits per second")),
output_field: None,
};
model.graphql = Some(Graphql {
backends: vec![GraphqlBackend::AsyncGraphql(AsyncGraphql {
skipped: Vec::new(),
attrs: quote::quote!(complexity = 5),
fields: vec![
field("checksum", "bitRate", ty("u64")),
field("cover_id", "coverId", generic("Option", "Uuid7")),
],
})],
input: RustSafeName::from_ident(&default_input_name(&base)),
output: RustSafeName::from_ident(&default_output_name(&base)),
key_output: RustSafeName::from_ident(&default_key_output_name(&base)),
key_object: None,
key_argument: None,
filter: RustSafeName::from_ident(&default_filter_name(&base)),
plural: None,
connection: None,
edge: None,
skipped: Vec::new(),
});
model
}
fn wire_only() -> RecordModel {
let mut model = video_track();
let base = model.record.clone();
model.graphql = Some(Graphql {
backends: vec![GraphqlBackend::AsyncGraphql(AsyncGraphql {
skipped: Vec::new(),
attrs: proc_macro2::TokenStream::new(),
fields: Vec::new(),
})],
input: RustSafeName::from_ident(&default_input_name(&base)),
output: RustSafeName::from_ident(&default_output_name(&base)),
key_output: RustSafeName::from_ident(&default_key_output_name(&base)),
key_object: None,
key_argument: None,
filter: RustSafeName::from_ident(&default_filter_name(&base)),
plural: None,
connection: None,
edge: None,
skipped: Vec::new(),
});
model
}
fn ordered() -> RecordModel {
let mut model = wired();
let key = |name: &str| persist_column(name, name, ty("Uuid7"));
for database in model
.persist
.iter_mut()
.flat_map(|persist| &mut persist.backends)
{
let storage = storage_of(database);
let mut columns = vec![key("media_id"), key("video_id"), key("id")];
columns.append(&mut storage.columns);
storage.columns = columns;
}
let postgres = model
.persist
.iter_mut()
.flat_map(|persist| &mut persist.backends)
.find(|database| database.kind() == DatabaseKind::Postgres)
.expect("`wired` stores a postgres row");
storage_of(postgres).columns[2].name = RustSafeName::new("pk", proc_macro2::Span::call_site());
model
}
pub(crate) fn queried() -> RecordModel {
let mut model = ordered();
for database in model
.persist
.iter_mut()
.flat_map(|persist| &mut persist.backends)
{
storage_of(database).into = fallible(path("path::to::raise"));
}
model
}
#[test]
fn the_wire_types_carry_no_backend_derive_and_no_backend_attribute() {
let file = emission(&wired());
let stated = |name: &str, attrs: &[syn::Attribute]| {
let attrs: Vec<String> = attrs
.iter()
.filter(|attr| !attr.path().is_ident("doc"))
.map(tight)
.collect();
assert!(
attrs.iter().all(|attr| attr.starts_with("#[derive(")),
"`{name}` carries a non-derive attribute: {attrs:?}"
);
assert!(
!attrs.iter().any(|attr| attr.contains("graphql")),
"`{name}` names a backend: {attrs:?}"
);
};
for name in [
"VideoTrackGraphqlInput",
"VideoTrackGraphqlOutput",
"VideoTrackKeyOutput",
"VideoTrackFilter",
] {
let item = struct_named(&file, name);
stated(name, &item.attrs);
assert!(
field_attrs(item).is_empty(),
"`{name}` puts a backend attribute on a field: {:?}",
field_attrs(item)
);
}
let order_by = enum_named(&file, "VideoTrackOrderBy");
stated("VideoTrackOrderBy", &order_by.attrs);
for variant in &order_by.variants {
assert!(
variant.attrs.iter().all(|attr| attr.path().is_ident("doc")),
"`VideoTrackOrderBy::{}` puts a backend attribute on a variant",
variant.ident
);
}
let wired = wired();
let backend = &wired.graphql.as_ref().expect("wired").backends[0];
assert_eq!(
backend.fields()[0].output.name.to_string(),
"bitRate",
"and the SDL name the derive round needs is on the MODEL, not thrown away"
);
assert_eq!(
backend.kind().output_object(),
"::async_graphql::Object",
"and the output's face is the ACCESSOR attribute — `SimpleObject` would publish layer 1, the \
`pub(crate)` substrate no rename word may move, so the field-rendering derive cannot be what \
an output object is written with"
);
assert_eq!(
backend.kind().order_by_derive(),
"::async_graphql::OneofObject",
"and the order-by's is the ONEOF derive — the plain `Enum` one would render bare column names, \
which is the face this stopped being"
);
let output = struct_named(&file, "VideoTrackGraphqlOutput");
assert_eq!(
fields(output),
["id", "key", "checksum", "cover_id"],
"the framework's two address members lead, and every member after them is the RECORD FIELD's \
own name — `checksum` is exposed as `bitRate` and the struct never says so, the schema name \
being the client's and the camelCase the backend's own act"
);
}
#[test]
fn every_emitted_wire_member_carries_the_substrate_visibility() {
let file = emission(&ordered());
for name in [
"VideoTrackGraphqlInput",
"VideoTrackGraphqlOutput",
"VideoTrackKeyOutput",
"VideoTrackFilter",
] {
let item = struct_named(&file, name);
let spelled: Vec<String> = named(item).iter().map(|field| tight(&field.vis)).collect();
assert!(!spelled.is_empty(), "`{name}` emits no member to check");
assert!(
spelled.iter().all(|vis| vis == "pub(crate)"),
"`{name}` does not spell every member `pub(crate)`: {spelled:?}"
);
}
}
#[test]
fn the_output_field_word_moves_the_accessor_and_leaves_the_member() {
let mut model = wired();
match &mut model.graphql.as_mut().expect("wired").backends[0] {
GraphqlBackend::AsyncGraphql(backend) => backend.fields[0].output_field = Some(ident("mass")),
}
let file = emission(&model);
let output = struct_named(&file, "VideoTrackGraphqlOutput");
assert_eq!(
fields(output),
["id", "key", "checksum", "cover_id"],
"LAYER 1: the member is the RECORD FIELD's name, and `field = \"mass\"` did not move it"
);
assert_eq!(
methods_of(&file, "VideoTrackGraphqlOutput"),
[
"id_ref",
"key_ref",
"mass_ref",
"cover_id_ref",
"__async_graphql_id",
"__async_graphql_key",
"__async_graphql_checksum",
"__async_graphql_cover_id"
],
"LAYER 2: the accessor is what the word moved — `checksum_ref` is gone and `mass_ref` is there, \
while the field that named no word keeps its own. LAYER 1 AND LAYER 2 ARE BOTH VISIBLE HERE, \
and their independence is the whole claim: the WIRE face's methods are named after the members \
— `__async_graphql_checksum`, whose stem the word did not move — and read through the \
accessors above them, so the two axes cannot collide and a rename on either leaves the other \
alone. The PREFIX is on the wire methods and on nothing else: an accessor is the Rust read \
road and keeps its name."
);
let body = tight(&method_of(&file, "VideoTrackGraphqlOutput", "mass_ref").block);
assert!(
body.contains("&self.checksum"),
"the moved accessor reads the PINNED member, which is what keeps the two layers one value: \
{body}"
);
let crossing = tight(&file);
assert!(
crossing.contains("checksum:"),
"and the row crossing fills that same member — an emitted-to-emitted write, so it names layer \
1 and never the face"
);
assert!(
!crossing.contains("mass:"),
"…and names the accessor's word nowhere: a crossing writing `mass:` would be `E0560` inside \
the expansion"
);
let backend = &model.graphql.as_ref().expect("wired").backends[0];
assert_eq!(
(
backend.fields()[0].output.name.to_string(),
backend.fields()[0].accessor().to_string()
),
("bitRate".to_owned(), "mass".to_owned()),
"LAYER 3 is untouched by either — the schema name is still on the model for the derive round"
);
}
#[test]
fn one_column_carries_four_names_and_each_stays_in_its_layer() {
let model = wired();
let file = emission(&model);
assert_eq!(
fields(struct_named(&file, "VideoTrackFilter"))[0],
"checksum"
);
assert_eq!(
fields(struct_named(&file, "VideoTrackSqliteComparison"))[0],
"checksum"
);
assert_eq!(
fields(struct_named(&file, "VideoTrackRecordComparison"))[0],
"checksum",
"the POSTGRES comparison too, and it is the one that proves the point: its column is renamed \
again, so a member following the rendered name would differ from sqlite's and an interface's \
consistency equation could not name one accessor for both"
);
assert_eq!(
enum_named(&file, "VideoTrackOrderBy").variants[0].ident,
"Checksum",
"and the order-by VARIANT, which is what the `OneofObject` derive renders as a schema key"
);
let backend = &model.graphql.as_ref().expect("wired").backends[0];
let (member, sdl, _) = backend.filter_field(model.stored_columns()[0]);
assert_eq!(
(member.to_string(), sdl),
("checksum".to_owned(), "bitRate".to_owned())
);
assert!(
tight(&method_of(&file, "VideoTrackOrderBy", "sqlite_column").block).contains("\"bitrate\""),
"sqlite still renders its own column name"
);
assert!(
tight(&method_of(&file, "VideoTrackOrderBy", "postgres_column").block)
.contains("\"bit_rate_v2\""),
"and postgres still renders its own"
);
let lowering = tight(&file);
assert!(
lowering.contains("FieldName::new(\"bitrate\")")
&& lowering.contains("FieldName::new(\"bit_rate_v2\")"),
"and each comparison pushes its OWN database's column as the address frame, off a member both \
of them spell `checksum`"
);
}
#[test]
fn an_order_by_variant_is_the_record_field_whatever_storage_renamed() {
let mut model = ordered();
let first = model
.persist
.as_mut()
.expect("ordered persists")
.backends
.first_mut()
.expect("a first database");
storage_of(first).columns[3].name =
RustSafeName::new("renamed_here", proc_macro2::Span::call_site());
let file = emission(&model);
let variants: Vec<String> = enum_named(&file, "VideoTrackOrderBy")
.variants
.iter()
.map(|variant| variant.ident.to_string())
.collect();
assert_eq!(
variants,
["MediaId", "VideoId", "Id", "Checksum", "CoverId"],
"the record's own field names — `RenamedHere` is what this list used to hold, and it was a \
storage name in a client's query document"
);
assert!(
tight(&method_of(&file, "VideoTrackOrderBy", "sqlite_column").block).contains(
"Self::Checksum(_)=>::core::result::Result::Ok(\
::ingraph::__private::field::FieldName::new(\"renamed_here\"))"
),
"…while the rename still reaches the SQL the resolver renders, which is the whole of what it \
was ever for"
);
}
#[test]
fn the_filter_takes_the_stored_columns() {
let mut model = wired();
match &mut model.graphql.as_mut().expect("wired").backends[0] {
GraphqlBackend::AsyncGraphql(backend) => backend.fields.pop(),
};
let file = emission(&model);
let filter = struct_named(&file, "VideoTrackFilter");
assert_eq!(
fields(filter),
["checksum", "cover_id"],
"`cover_id` is no longer exposed on the output and is still filterable — and BOTH members are \
the record field's own name. `checksum` is exposed with `input(rename = \"bitRate\")` and the \
member does not follow it, a wire word moving the schema name alone; `cover_id` declares no \
wire name at all and takes its field's"
);
let types: Vec<String> = named(filter).iter().map(|f| tight(&f.ty)).collect();
assert_eq!(
types,
[
"::core::option::Option<<<u64as::ingraph::__private::marker::DefaultMarker>::Markeras::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilter>",
"::core::option::Option<<<Option<Uuid7>as::ingraph::__private::marker::DefaultMarker>::Markeras::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilter>"
],
"each field its type's FILTER, not its value — so a client gets the whole operator vocabulary, \
and a nullable column keeps its three states because the null test rides its filter. The \
domain type is written VERBATIM and asked TWICE: what it MEANS, then what guards that \
meaning. Stripping the `Option` here would hand a nullable column the filter of a `NOT NULL` \
one, and picking the marker here instead of asking the type would read an aliased collection \
as a scalar."
);
}
#[test]
fn a_declared_marker_replaces_the_inference_in_every_projection() {
let mut model = wired();
label(
&mut model,
"checksum",
Marker::Framework(FrameworkMarker {
label: Label::Set,
element: None,
}),
);
label(
&mut model,
"cover_id",
Marker::Path(syn::parse_quote!(their::RollMarker)),
);
let file = emission(&model);
let shorthand = "<::ingraph::__private::marker::SetMarker<u64>as::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilter";
let declared = "<their::RollMarker<Option<Uuid7>>as::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilter";
assert_eq!(
named(struct_named(&file, "VideoTrackFilter"))
.iter()
.map(|field| tight(&field.ty))
.collect::<Vec<_>>(),
[
format!("::core::option::Option<{shorthand}>"),
format!("::core::option::Option<{declared}>")
],
"a word reaches the framework's own marker through the shelf; a path is carried verbatim, \
because it resolves in the DECLARER's namespace and nowhere else"
);
let db = database_parameter();
assert_eq!(
named(struct_named(&file, "VideoTrackSqliteComparison"))
.iter()
.map(|field| tight(&field.ty))
.collect::<Vec<_>>(),
[
format!(
"<{shorthand}as::ingraph::__private::comparison::ToDatabaseComparison<u64,{db}>>::Comparison"
),
format!(
"<{declared}as::ingraph::__private::comparison::ToDatabaseComparison<Option<Uuid7>,{db}>>::Comparison"
)
],
"and the crossing starts from the SAME filter, so a column cannot end up with two"
);
}
fn optional_collections() -> RecordModel {
let mut model = model("Strip", &[], "id");
let record = model.record.clone();
model.fields = [
("tags", syn::parse_quote!(Option<Vec<String>>)),
("labels", syn::parse_quote!(Vec<String>)),
("cover", syn::parse_quote!(Option<Vec<u8>>)),
]
.into_iter()
.map(|(name, ty)| Field {
column: column_of(name, ty),
identity: false,
marker: None,
sortable: false,
indexed: false,
reference: None,
skip: None,
docs: Vec::new(),
condition: Condition::always(),
build: Build::default(),
})
.collect();
let column = |name: &str, ty: syn::Type| persist_column(name, name, ty);
model.persist = Some(Persist {
backends: vec![stored(
&record,
DatabaseKind::Sqlite,
vec![
column("tags", syn::parse_quote!(Option<Vec<String>>)),
column("labels", syn::parse_quote!(Vec<String>)),
column("cover", syn::parse_quote!(Option<Vec<u8>>)),
],
)],
table: None,
});
let face = |name: &str| Face {
name: RustSafeName::new(name, proc_macro2::Span::call_site()),
attrs: proc_macro2::TokenStream::new(),
};
let field = |source: &str, ty: syn::Type| GraphqlField {
source: ident(source),
domain: ty,
wire: None,
output_crossing: WirePosition::default(),
input_crossing: WirePosition::default(),
input: face(source),
output: face(source),
output_field: None,
};
model.graphql = Some(Graphql {
backends: vec![GraphqlBackend::AsyncGraphql(AsyncGraphql {
skipped: Vec::new(),
attrs: proc_macro2::TokenStream::new(),
fields: vec![
field("tags", syn::parse_quote!(Option<Vec<String>>)),
field("labels", syn::parse_quote!(Vec<String>)),
field("cover", syn::parse_quote!(Option<Vec<u8>>)),
],
})],
input: RustSafeName::from_ident(&default_input_name(&record)),
output: RustSafeName::from_ident(&default_output_name(&record)),
key_output: RustSafeName::from_ident(&default_key_output_name(&record)),
key_object: None,
key_argument: None,
filter: RustSafeName::from_ident(&default_filter_name(&record)),
plural: None,
connection: None,
edge: None,
skipped: Vec::new(),
});
for name in ["tags", "labels"] {
label(
&mut model,
name,
Marker::Framework(FrameworkMarker {
label: Label::List,
element: None,
}),
);
}
model
}
#[test]
fn a_column_one_database_narrows_away_keeps_the_shared_vocabulary() {
let mut model = wired();
let persist = model.persist.as_mut().expect("stored");
let taken = storage_of(&mut persist.backends[1]).columns.remove(0);
assert!(
model.persist.as_ref().expect("stored").backends[0]
.columns()
.iter()
.any(|column| column.source == taken.source),
"the column is still a column of the database that kept it"
);
assert!(
model
.stored_columns()
.iter()
.any(|column| column.source == taken.source),
"and it stays in the shared list, which every wire vocabulary is built from"
);
assert!(
model
.queried_columns()
.iter()
.any(|(_, column)| column.source == taken.source),
"so the filter still names it"
);
assert!(
model
.ordered_columns()
.iter()
.any(|(_, column)| column.source == taken.source),
"and so does an order"
);
assert_eq!(
model
.stored_columns()
.iter()
.map(|column| column.source.to_string())
.collect::<Vec<_>>(),
model.persist.as_ref().expect("stored").backends[0]
.columns()
.iter()
.map(|column| column.source.to_string())
.collect::<Vec<_>>(),
"the shared list is the declaring order, taken from the database that has every column"
);
assert_eq!(
model.persist.as_ref().expect("stored").backends[1]
.compared(&model)
.len(),
model.queried_columns().len() - 1,
"the narrowing database's comparison is one member shorter than the filter"
);
assert!(
!model.persist.as_ref().expect("stored").backends[1]
.compared(&model)
.iter()
.any(|column| column.source == taken.source),
"and the member it is short of is the narrowed one"
);
assert_eq!(
model.persist.as_ref().expect("stored").backends[0]
.compared(&model)
.len(),
model.queried_columns().len(),
"while the database that kept every column compares every one of them"
);
}
#[test]
fn a_composite_column_is_orderable_in_neither_face() {
let file = emission(&composed());
let variants = |item: &syn::ItemEnum| -> Vec<String> {
item
.variants
.iter()
.map(|variant| variant.ident.to_string())
.collect()
};
assert_eq!(
variants(enum_named(&file, "MediaOrderBy")),
["Id", "Chapters", "CoverId"],
"the `flatten` column is gone and its neighbours are untouched"
);
assert_eq!(
variants(enum_named(&file, "MediaSqliteCursor")),
["Id", "Chapters", "CoverId"],
"and the cursor value carries exactly the same set, from the same fence"
);
let plain = emission(&whole_row());
assert_eq!(
variants(enum_named(&plain, "MediaOrderBy")),
["Id", "Checksum", "Chapters", "CoverId"],
"an UNMARKED composite is a scalar to anything holding tokens, and stays in"
);
}
#[test]
fn a_collection_word_is_an_order_subject_and_not_a_cursor_slot() {
let model = optional_collections();
assert_eq!(
model
.stored_columns()
.iter()
.map(|column| column.name.to_string())
.collect::<Vec<_>>(),
["tags", "labels", "cover"],
"all three are stored, and the word is what tells them apart rather than participation"
);
assert!(
model
.fields
.iter()
.all(|field| field.column.project == Projection::Borrowed),
"and not one of them writes `repeated`, which is the OTHER axis this must not read"
);
let variants = |item: &syn::ItemEnum| -> Vec<String> {
item
.variants
.iter()
.map(|variant| variant.ident.to_string())
.collect()
};
let file = emission(&model);
assert_eq!(
variants(enum_named(&file, "StripOrderBy")),
["Tags", "Labels", "Cover"],
"the two `list` columns are order subjects, beside the blob that was never in question"
);
let paged = emission(&gathered());
assert_eq!(
variants(enum_named(&paged, "MediaOrderBy")),
["Id", "Checksum", "Chapters", "CoverId"],
"the collection is an order subject here too"
);
assert_eq!(
variants(enum_named(&paged, "MediaSqliteCursor")),
["Id", "Checksum", "CoverId"],
"and on SQLite, where it is edge-stored, it is the one column a cursor has no slot for"
);
}
#[test]
fn an_array_stored_collection_is_a_cursor_slot_holding_the_whole_list() {
let variants = |item: &syn::ItemEnum| -> Vec<String> {
item
.variants
.iter()
.map(|variant| variant.ident.to_string())
.collect()
};
let postgres = emission(&gathered_in_postgres());
assert_eq!(
variants(enum_named(&postgres, "MediaOrderBy")),
["Id", "Checksum", "Chapters", "CoverId"],
"the order-by is what it was"
);
assert_eq!(
variants(enum_named(&postgres, "MediaPostgresCursor")),
["Id", "Checksum", "Chapters", "CoverId"],
"and the array-stored collection now has a slot of its own"
);
let slot = enum_named(&postgres, "MediaPostgresCursor")
.variants
.iter()
.find(|variant| variant.ident == "Chapters")
.expect("the collection has a slot");
assert_eq!(
tight(&slot.fields),
"(::std::vec::Vec<Uuid7>)",
"and the slot holds the LIST, which is what the row's field holds"
);
let worded = emission(&edge_declared_in_postgres());
assert_eq!(
variants(enum_named(&worded, "MediaOrderBy")),
["Id", "Checksum", "Chapters", "CoverId"],
"still an order subject, which is the term's own answer"
);
assert_eq!(
variants(enum_named(&worded, "MediaPostgresCursor")),
["Id", "Checksum", "CoverId"],
"and no slot, on the same dialect, because the storage form is what decides"
);
}
#[test]
fn the_row_projects_a_value_at_an_array_stored_collection_and_none_at_an_edge_stored_one() {
let value_of = |model: &RecordModel| -> String {
let file = emission(model);
let ordering = wrote(&file, "SqlOrdering").expect("the page binding is emitted");
let value = methods(ordering)
.into_iter()
.find(|method| method.sig.ident == "value")
.expect("the row's projection into cursor values");
tight(&value.block)
};
let array = value_of(&gathered_in_postgres());
assert!(
array.contains(
"MediaOrderBy::Chapters(_)=>::core::result::Result::Ok(::core::option::Option::Some(\
MediaPostgresCursor::Chapters(::core::clone::Clone::clone(&self.chapters)),))"
),
"the array-stored collection projects the row's whole list: {array}"
);
let worded = value_of(&edge_declared_in_postgres());
assert!(
worded.contains(
"MediaOrderBy::Chapters(_)=>::core::result::Result::Ok(::core::option::Option::None)"
),
"and the edge-stored one still declines, on the same dialect: {worded}"
);
}
#[test]
fn an_order_term_names_the_collection_s_storage_form() {
let term_of = |model: &RecordModel, kind: &str| -> String {
tight(&method_of(&emission(model), "MediaOrderBy", &format!("{kind}_term")).block)
};
let sqlite = term_of(&gathered(), "sqlite");
assert!(
sqlite.contains("Self::Chapters(direction)=>::ingraph::__private::cursor::OrderTerm::edge("),
"SQLite has no array type, so every collection is a table of its own: {sqlite}"
);
assert!(
sqlite.contains("Self::Id(direction)=>::ingraph::__private::cursor::OrderTerm::spanning("),
"and the scalars beside it take the width constructor, not the subject one: {sqlite}"
);
let postgres = term_of(&gathered_in_postgres(), "postgres");
assert!(
postgres.contains("Self::Chapters(direction)=>::ingraph::__private::cursor::OrderTerm::array("),
"the wordless default rides the row as a native array: {postgres}"
);
let worded = term_of(&edge_declared_in_postgres(), "postgres");
assert!(
worded.contains("Self::Chapters(direction)=>::ingraph::__private::cursor::OrderTerm::edge("),
"and the word sends the same column to a table of its own: {worded}"
);
}
#[test]
fn a_collection_classified_column_sheds_the_option_and_a_blob_keeps_it() {
let file = emission(&optional_collections());
let marker = "::ingraph::__private::marker";
let shelf = "::ingraph::__private::graphql";
let listed =
format!("<{marker}::ListMarker<Vec<String>>as{shelf}::ToGraphqlFilter>::ColumnFilter");
let inferred = format!(
"<<Option<Vec<u8>>as{marker}::DefaultMarker>::Markeras{shelf}::ToGraphqlFilter>::ColumnFilter"
);
assert_eq!(
named(struct_named(&file, "StripFilter"))
.iter()
.map(|field| tight(&field.ty))
.collect::<Vec<_>>(),
[
format!("::core::option::Option<{listed}>"),
format!("::core::option::Option<{listed}>"),
format!("::core::option::Option<{inferred}>")
],
"the optional collection and the bare one are one face, and the marker is applied to the \
COLLECTION — an `Option<Vec<String>>` inside the marker would carry the null test the ruling \
says the column does not have"
);
let db = database_parameter();
let crossing = |filter: &str, stored: &str| {
format!(
"<{filter}as::ingraph::__private::comparison::ToDatabaseComparison<{stored},{db}>>::Comparison"
)
};
assert_eq!(
named(struct_named(&file, "StripSqliteComparison"))
.iter()
.map(|field| tight(&field.ty))
.collect::<Vec<_>>(),
[
crossing(&listed, "Option<Vec<String>>"),
crossing(&listed, "Vec<String>"),
crossing(&inferred, "Option<Vec<u8>>")
],
"and the collapse reaches the crossing's SELF TYPE, which is where the `Nullable` wrapper would \
otherwise compose over a collection's comparison. The STORED type is untouched — it is the column's \
own declaration, and an edge-table column declares the ELEMENT type it keeps"
);
}
#[test]
fn an_alias_hiding_the_option_is_left_alone_and_a_qualified_one_is_not() {
let marker = "::ingraph::__private::marker";
let shelf = "::ingraph::__private::graphql";
let emitted = |domain: syn::Type| {
let mut model = optional_collections();
let Some(persist) = model.persist.as_mut() else {
panic!("the model stores its columns")
};
storage_of(&mut persist.backends[0]).columns[0].domain = domain.clone();
match &mut model.graphql.as_mut().expect("wired").backends[0] {
GraphqlBackend::AsyncGraphql(backend) => backend.fields[0].domain = domain,
}
let file = emission(&model);
tight(&named(struct_named(&file, "StripFilter"))[0].ty)
};
assert_eq!(
emitted(syn::parse_quote!(MaybeTags)),
format!(
"::core::option::Option<<{marker}::ListMarker<MaybeTags>as{shelf}::ToGraphqlFilter>::ColumnFilter>"
),
"an alias is carried verbatim — the emitter cannot see through one, and the column is refused \
at the declaration rather than resolved to the wrapped filter"
);
assert_eq!(
emitted(syn::parse_quote!(core::option::Option<Vec<String>>)),
format!(
"::core::option::Option<<{marker}::ListMarker<Vec<String>>as{shelf}::ToGraphqlFilter>::ColumnFilter>"
),
"and a written `Option` is one however it is spelled"
);
}
#[test]
fn the_comparison_holds_a_crossing_per_column_per_database() {
let file = emission(&wired());
let db = database_parameter();
let types = |name: &str| -> Vec<String> {
named(struct_named(&file, name))
.iter()
.map(|field| tight(&field.ty))
.collect()
};
let held = |domain: &str, stored: &str| {
format!(
"<<<{domain}as::ingraph::__private::marker::DefaultMarker>::Markeras::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilteras::ingraph::__private::comparison::ToDatabaseComparison<{stored},{db}>>::Comparison"
)
};
assert_eq!(
types("VideoTrackSqliteComparison"),
[held("u64", "u64"), held("Option<Uuid7>", "Option<Uuid7>")]
);
assert_eq!(
types("VideoTrackRecordComparison"),
[held("u64", "BeU64"), held("Option<Uuid7>", "Option<Uuid7>")],
"the `type` override reaches the OPERANDS exactly as it reaches the row — one authority — and \
the filter is still chosen by the domain type, because storage is not the question"
);
assert_eq!(
fields(struct_named(&file, "VideoTrackRecordComparison")),
["checksum", "cover_id"],
"and the member is the RECORD FIELD's — LAYER 1. It used to be this database's column name, \
which gave one column two member names across two backends (`bit_rate_v2` here, `bitrate` on \
sqlite) and made an interface's consistency equation, which reads a member's comparison \
through an accessor built from the pinned field name, break on a neighbour's storage rename"
);
assert_eq!(
returns(method_of(
&file,
&format!("VideoTrackSqliteComparison<{db}>"),
"checksum_ref"
)),
format!("&{}", held("u64", "u64")),
"and the accessor hands back the KIND, not an `Option<&value>` — whether the column is compared \
at all is the kind's own emptiness, and a second encoding of one fact can disagree with the \
first"
);
}
#[test]
fn the_comparison_carries_no_derive_and_only_the_lowering() {
let file = emission(&wired());
let attrs: Vec<String> = struct_named(&file, "VideoTrackSqliteComparison")
.attrs
.iter()
.filter(|attr| !attr.path().is_ident("doc"))
.map(tight)
.collect();
assert!(attrs.is_empty(), "no derive survives the shape: {attrs:?}");
let written: Vec<String> = trait_impls(&file)
.into_iter()
.filter(|(item, _)| impl_of(item).starts_with("VideoTrackSqliteComparison"))
.map(|(_, path)| tight(path))
.collect();
assert_eq!(
written,
[format!(
"::ingraph::__private::comparison::ComplexComparison<{}>",
database_parameter()
)],
"the LOWERING is the one impl the type carries, and it needs none of the three: its body calls \
the trait methods the crossing's item bound already promises of each field"
);
}
#[test]
fn the_comparison_gains_the_constructor_the_shape_took_away() {
let db = database_parameter();
let file = emission(&wired());
let new = method_of(&file, &format!("VideoTrackSqliteComparison<{db}>"), "new");
assert!(
is_const(new),
"moving a predicate into a struct drops nothing"
);
let parameters: Vec<String> = new
.sig
.inputs
.iter()
.map(|input| match input {
syn::FnArg::Typed(typed) => tight(&typed.pat),
syn::FnArg::Receiver(_) => panic!("`new` takes no self"),
})
.collect();
assert_eq!(
parameters,
["checksum", "cover_id"],
"in column order, each named by the record field it compares"
);
assert_eq!(
tight(&new.sig.output),
"->Self",
"the comparison, not a builder — it has no invariant to guard"
);
assert_eq!(
methods_of(&file, &format!("VideoTrackSqliteComparison<{db}>")),
["new", "checksum_ref", "cover_id_ref"],
"`new`, then each column's borrow — no mutators, because a predicate is built and then lowered"
);
}
#[test]
fn a_database_with_no_column_gets_a_nullary_constructor() {
let mut model = wired();
for database in model
.persist
.iter_mut()
.flat_map(|persist| &mut persist.backends)
{
storage_of(database).columns.clear();
}
let file = emission(&model);
let new = method_of(
&file,
&format!("VideoTrackSqliteComparison<{}>", database_parameter()),
"new",
);
assert!(new.sig.inputs.is_empty());
assert_eq!(
tight(&new.block),
"{Self{db:::core::marker::PhantomData,}}",
"and the marker is filled in rather than left for `Default`, which this type does not have"
);
}
#[test]
fn a_database_with_no_column_gets_the_marker_and_no_other_does() {
let mut model = persisted();
for database in model
.persist
.iter_mut()
.flat_map(|persist| &mut persist.backends)
{
storage_of(database).columns.clear();
}
let file = emission(&model);
assert_eq!(
named(struct_named(&file, "VideoTrackSqliteComparison"))
.iter()
.map(|field| tight(&field.ty))
.collect::<Vec<String>>(),
[format!(
"::core::marker::PhantomData<fn()->{}>",
database_parameter()
)]
);
assert!(
!fields(struct_named(
&emission(&persisted()),
"VideoTrackSqliteComparison"
))
.contains(&"db".to_owned())
);
}
#[test]
fn the_lowering_is_emitted_and_the_crossing_from_a_filter_is_not() {
let file = emission(&wired());
let by = |needle: &str| -> Vec<String> {
trait_impls(&file)
.into_iter()
.filter(|(_, path)| tight(path).contains(needle))
.map(|(item, path)| format!("{} for {}", tight(path), impl_of(item)))
.collect()
};
assert!(
by("FromFilter").is_empty(),
"a filter carries no VALUES into a comparison: the bound that would say so cannot be stated \
here, and cannot move onto the map either — the edge-table strategy is constructed with \
addressing the filter does not carry: {:?}",
by("FromFilter")
);
let db = database_parameter();
assert_eq!(
by("ComplexComparison"),
[
format!(
"::ingraph::__private::comparison::ComplexComparison<{db}> for VideoTrackSqliteComparison<{db}>"
),
format!(
"::ingraph::__private::comparison::ComplexComparison<{db}> for VideoTrackRecordComparison<{db}>"
),
format!(
"::ingraph::__private::comparison::ComplexComparison<{db}> for VideoTrackMongoComparison<{db}>"
),
],
"one per database, and each is what discharges the item bound the map's associated type carries"
);
assert!(names(&file).contains(&"VideoTrackRecordComparison".to_owned()));
}
#[test]
fn the_lowering_rides_with_the_comparison_rather_than_with_the_map() {
let db = database_parameter();
let file = emission(&persisted());
let lowerings: Vec<String> = trait_impls(&file)
.into_iter()
.filter(|(_, path)| tight(path).contains("ComplexComparison"))
.map(|(item, _)| impl_of(item))
.collect();
assert_eq!(
lowerings,
[
format!("VideoTrackSqliteComparison<{db}>"),
format!("VideoTrackRecordComparison<{db}>"),
format!("VideoTrackMongoComparison<{db}>"),
],
"no filter is declared, so no map is emitted — and the lowering is still here"
);
let mut model = persisted();
for database in model
.persist
.iter_mut()
.flat_map(|persist| &mut persist.backends)
{
storage_of(database).columns.clear();
}
let file = emission(&model);
let empty = trait_impls(&file)
.into_iter()
.find(|(item, path)| {
tight(path).contains("ComplexComparison") && impl_of(item).starts_with("VideoTrackSqlite")
})
.map(|(item, _)| tight(item))
.expect("the empty comparison lowers too");
assert!(
empty.contains("fnconjuncts(&self)->::core::primitive::usize{0}"),
"a comparison with no column renders no conjunct: {empty}"
);
assert!(
empty.contains("::core::result::Result::Ok(__ingraph_builder)"),
"and hands the accumulator straight back: {empty}"
);
}
fn vocabularies(file: &syn::File) -> Vec<(String, Vec<String>)> {
trait_impls(file)
.into_iter()
.filter(|(_, path)| {
let shelved: Vec<String> = path
.segments
.iter()
.skip_while(|segment| segment.ident != "__private")
.skip(1)
.map(|segment| segment.ident.to_string())
.collect();
shelved == ["transform", "Record"]
})
.map(|(item, path)| {
let backend = storage_argument(path).expect("the vocabulary names its backend");
let bound: Vec<String> = item
.items
.iter()
.filter_map(|item| match item {
syn::ImplItem::Type(bound) => Some(tight(&bound.ty)),
_ => None,
})
.collect();
(backend, bound)
})
.collect()
}
#[test]
fn the_vocabulary_is_one_impl_per_declared_database_at_a_concrete_backend() {
const SQLITE: &str = "::ingraph::__private::sqlx::Sqlite";
const POSTGRES: &str = "::ingraph::__private::sqlx::Postgres";
const MONGO: &str = "::ingraph::__private::comparison::mongo::Mongo";
const ORDER: &str = "VideoTrackOrderBy";
assert_eq!(
vocabularies(&emission(&persisted())),
[
(
SQLITE.to_owned(),
vec![
"VideoTrackSqlite".to_owned(),
format!("VideoTrackSqliteComparison<{SQLITE}>"),
ORDER.to_owned(),
]
),
(
POSTGRES.to_owned(),
vec![
"VideoTrackRecord".to_owned(),
format!("VideoTrackRecordComparison<{POSTGRES}>"),
ORDER.to_owned(),
]
),
(
MONGO.to_owned(),
vec![
"VideoTrackMongo".to_owned(),
format!("VideoTrackMongoComparison<{MONGO}>"),
ORDER.to_owned(),
]
),
]
);
}
#[test]
fn a_record_that_persists_nowhere_answers_no_vocabulary() {
let model = video_track();
assert!(model.persist.is_none(), "the fixture is pure compute");
assert!(vocabularies(&emission(&model)).is_empty());
assert!(gated(&model).is_empty(), "and nothing rides a gate");
}
#[test]
fn the_vocabulary_rides_its_databases_gate_and_nothing_else_does() {
let record = |backend: &str| {
vec![format!(
"::ingraph::__private::transform::Record<{backend}> for VideoTrack"
)]
};
assert_eq!(
gated(&persisted()),
[
(
"if_sqlite".to_owned(),
record("::ingraph::__private::sqlx::Sqlite")
),
(
"if_postgres".to_owned(),
record("::ingraph::__private::sqlx::Postgres")
),
("if_mongo".to_owned(), Vec::new()),
(
"if_mongo".to_owned(),
record("::ingraph::__private::comparison::mongo::Mongo")
),
]
);
}
fn flattened() -> RecordModel {
let mut model = persisted();
flatten_the_first_sql_column(&mut model);
model
}
#[test]
fn a_flattened_column_pushes_no_frame_and_every_other_column_still_does() {
let file = emission(&flattened());
let lowering = trait_impls(&file)
.into_iter()
.find(|(item, path)| {
tight(path).contains("ComplexComparison") && impl_of(item).starts_with("VideoTrackSqlite")
})
.map(|(item, _)| tight(item))
.expect("the sqlite lowering");
assert!(
lowering.contains("apply(&self.checksum,__ingraph_at,__ingraph_builder,)"),
"the marked column is applied at the address this comparison was handed, and it is read through \
the MEMBER — layer 1, the record field's name, where the frame below is the SQL string: \
{lowering}"
);
assert!(
!lowering.contains("FieldName::new(\"bitrate\")"),
"and no segment is made for it at all: {lowering}"
);
assert!(
lowering.contains("FieldName::new(\"cover_id\")"),
"while the unmarked column beside it still pushes its own: {lowering}"
);
}
#[test]
fn a_flattened_column_states_the_refined_crossing_and_no_other_column_does() {
let file = emission(&flattened());
let clause = tight(
struct_named(&file, "VideoTrackSqliteComparison")
.generics
.where_clause
.as_ref()
.expect("the comparison assumes its crossings"),
);
assert!(
clause.contains("ToFlattenedComparison<u64,"),
"the marked column's crossing is the refined one: {clause}"
);
assert!(
clause.contains("ToDatabaseComparison<Option<Uuid7>,"),
"and the unmarked column's is the plain one: {clause}"
);
assert!(
!clause.contains("ToFlattenedComparison<Option<Uuid7>,"),
"nothing else picks up the refinement: {clause}"
);
assert!(
!tight(
struct_named(&emission(&persisted()), "VideoTrackSqliteComparison")
.generics
.where_clause
.as_ref()
.expect("the comparison assumes its crossings")
)
.contains("ToFlattenedComparison"),
"and an unmarked declaration states it nowhere"
);
}
#[test]
fn a_flattened_column_is_read_without_a_name_and_every_other_column_with_one() {
assert_eq!(
decoded(&emission(&flattened()), "VideoTrackSqlite"),
[
("bitrate".to_owned(), None),
("cover_id".to_owned(), Some("cover_id".to_owned())),
],
);
assert_eq!(
decoded(&emission(&persisted()), "VideoTrackSqlite"),
binds(&[("bitrate", "bitrate"), ("cover_id", "cover_id")]),
"and the same declaration without the word names both"
);
}
#[test]
fn every_sql_rows_rendered_names_are_fenced_one_field_at_a_time() {
let emitted = tight(emission(&persisted()));
for (at, column) in ["bitrate", "cover_id"].into_iter().enumerate() {
assert!(
emitted.contains(&format!("distinct(__INGRAPH_COLUMNS__,{at}usize)")),
"the {at}th field is fenced: {emitted}"
);
assert!(
emitted.contains(&format!("wouldrender`{column}`intoacolumn")),
"and the sentence names `{column}`: {emitted}"
);
}
for row in ["VideoTrackSqlite", "VideoTrackRecord"] {
assert!(
emitted.contains(&format!("`{row}`wouldrender")),
"both SQL rows carry one: {emitted}"
);
}
assert!(
!emitted.contains("`VideoTrackMongo`wouldrender"),
"while the document family has no `flatten` to fence: {emitted}"
);
}
#[test]
fn a_document_names_every_column_whatever_the_sql_rows_flattened() {
assert_eq!(
field_attrs(struct_named(&emission(&flattened()), "VideoTrackMongo")),
[
"#[serde(rename=\"bitrate\",with=\"::ingraph::__private::query::mongo::via\")]",
"#[serde(rename=\"cover_id\",with=\"::ingraph::__private::query::mongo::via\")]"
]
);
}
#[test]
fn a_comparison_is_emitted_without_a_wire_face() {
let file = emission(&persisted());
assert!(names(&file).contains(&"VideoTrackSqliteComparison".to_owned()));
assert!(
!trait_impls(&file)
.iter()
.any(|(_, path)| tight(path).contains("Filter")),
"and nothing converts into it, because there is no filter to convert from"
);
}
#[test]
fn the_comparison_follows_the_rows_name() {
assert_eq!(
default_comparison_name(&ident("VideoTrackRecord")),
"VideoTrackRecordComparison"
);
}
#[test]
fn the_wire_face_declares_only_the_authorised_trait_impl() {
let model = wired();
let file = emission(&model);
let framework = unauthorised_framework_impls(&model, &file);
assert!(framework.is_empty(), "{framework:?}");
assert!(framework_paths_not_through_a_private_module(&model).is_empty());
}
#[test]
fn the_filter_maps_to_each_databases_comparison_through_its_row() {
let file = emission(&wired());
let maps: Vec<(String, String)> = trait_impls(&file)
.into_iter()
.filter(|(_, path)| tight(path).contains("ToDatabaseComparison"))
.map(|(item, path)| {
let comparison = item
.items
.iter()
.find_map(|item| match item {
syn::ImplItem::Type(item) => Some(tight(&item.ty)),
_ => None,
})
.expect("the map names a comparison");
(format!("{} for {}", tight(path), impl_of(item)), comparison)
})
.collect();
let db = database_parameter();
let map = |row: &str, comparison: &str| {
(
format!(
"::ingraph::__private::comparison::ToDatabaseComparison<{row},{db}> for VideoTrackFilter"
),
format!("{comparison}<{db}>"),
)
};
assert_eq!(
maps,
[
map("VideoTrackSqlite", "VideoTrackSqliteComparison"),
map("VideoTrackRecord", "VideoTrackRecordComparison"),
map("VideoTrackMongo", "VideoTrackMongoComparison"),
],
"one per declared database, keyed on that database's ROW — and a renamed row takes its \
comparison with it, which `VideoTrackRecord` is"
);
}
#[test]
fn the_map_assumes_exactly_what_the_comparison_assumes() {
let file = emission(&wired());
let clause = |item: &syn::ItemImpl| {
tight(
item
.generics
.where_clause
.as_ref()
.expect("the crossings are assumed"),
)
};
let map = trait_impls(&file)
.into_iter()
.find(|(item, path)| {
tight(path).contains("ToDatabaseComparison<VideoTrackSqlite") && impl_of(item) != "()"
})
.map(|(item, _)| clause(item))
.expect("the sqlite map");
let comparison = struct_named(&file, "VideoTrackSqliteComparison");
assert_eq!(
map,
tight(
comparison
.generics
.where_clause
.as_ref()
.expect("the comparison assumes its crossings")
)
);
}
const STD_NAMES: &[&str] = &[
"Debug",
"Clone",
"Copy",
"PartialEq",
"Eq",
"Hash",
"Default",
"Option",
"Result",
"Some",
"None",
"Ok",
"Err",
"From",
"TryFrom",
"Into",
"Box",
"Vec",
"String",
];
fn aliased(mut model: RecordModel) -> RecordModel {
for field in &mut model.fields {
field.column.ty = ty("MaybeCover");
}
for column in model.key.path.iter_mut().chain([&mut model.key.id]) {
column.ty = ty("Uuid7");
}
if let Some(lineage) = model.lineage.as_mut() {
for column in lineage.path_mut() {
column.ty = ty("Uuid7");
}
}
for database in model
.persist
.iter_mut()
.flat_map(|persist| &mut persist.backends)
{
for column in &mut storage_of(database).columns {
column.domain = ty("MaybeCover");
column.stored = column.stored.as_ref().map(|_| ty("StoredCover"));
}
}
for backend in model
.graphql
.iter_mut()
.flat_map(|graphql| &mut graphql.backends)
{
let GraphqlBackend::AsyncGraphql(backend) = backend;
for field in &mut backend.fields {
field.domain = ty("MaybeCover");
}
}
model
}
#[test]
fn every_std_name_the_emission_writes_is_absolutely_pathed() {
for model in [aliased(wired()), aliased(whole_row())] {
let bare = bare_std_names(&model);
assert!(
bare.is_empty(),
"`{}` writes a bare `std` name — it would resolve in the module the expansion lands in: \
{bare:?}",
model.record
);
}
}
fn bare_std_names(model: &RecordModel) -> Vec<String> {
fn flatten(stream: proc_macro2::TokenStream, into: &mut Vec<proc_macro2::TokenTree>) {
for tree in stream {
match tree {
proc_macro2::TokenTree::Group(group) => {
flatten(group.stream(), into);
}
other => into.push(other),
}
}
}
let mut tokens = Vec::new();
flatten(model.emit(), &mut tokens);
let colon = |at: usize| {
at < tokens.len()
&& matches!(&tokens[at], proc_macro2::TokenTree::Punct(p) if p.as_char() == ':')
};
(0..tokens.len())
.filter(|at| {
matches!(&tokens[*at], proc_macro2::TokenTree::Ident(id)
if STD_NAMES.contains(&id.to_string().as_str()))
})
.filter(|at| !(*at >= 2 && colon(at - 1) && colon(at - 2)))
.map(|at| {
tokens[at.saturating_sub(4)..(at + 1).min(tokens.len())]
.iter()
.map(ToString::to_string)
.collect::<String>()
})
.collect()
}
#[test]
fn the_filter_builders_take_and_return_filters() {
let file = emission(&wired());
let filter = "VideoTrackFilter";
let parameters: Vec<String> = method_of(&file, filter, "with_checksum")
.sig
.inputs
.iter()
.filter_map(|input| match input {
syn::FnArg::Typed(typed) => Some(tight(&typed.ty)),
syn::FnArg::Receiver(_) => None,
})
.collect();
assert_eq!(
parameters,
[
"<<u64as::ingraph::__private::marker::DefaultMarker>::Markeras::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilter"
],
"`with_*` takes the FILTER — its type changed and its role did not, which is why the verb did \
not change either"
);
assert_eq!(
returns(method_of(&file, filter, "checksum_ref")),
"::core::option::Option<&<<u64as::ingraph::__private::marker::DefaultMarker>::Markeras::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilter>",
"and the accessor hands back the filter, not a value"
);
}
#[test]
fn an_order_by_variant_resolves_to_a_field_name_per_database() {
let file = emission(&wired());
let order_by = "VideoTrackOrderBy";
for database in ["sqlite", "postgres", "mongo"] {
let resolver = method_of(&file, order_by, &format!("{database}_column"));
assert_eq!(
returns(resolver),
"::core::result::Result<&'static::ingraph::__private::field::FieldName,\
::ingraph::__private::query::ColumnNotStored>",
"`{database}_column` answers in the ordering seam's own type, or refuses by name"
);
assert!(is_const(resolver), "`{database}_column` is still const");
}
assert_eq!(
tight(&method_of(&file, order_by, "sqlite_column").block),
"{matchself{Self::Checksum(_)=>::core::result::Result::Ok(\
::ingraph::__private::field::FieldName::new(\"bitrate\")),\
Self::CoverId(_)=>::core::result::Result::Ok(\
::ingraph::__private::field::FieldName::new(\"cover_id\")),}}",
"every arm BUILDS the name — a bare literal would be the `&str` this stopped returning. The two \
halves of the arm are the two layers: the VARIANT is the record field (`Checksum`) and the \
name it resolves to is what sqlite renders (`bitrate`)"
);
assert_eq!(
tight(&method_of(&file, order_by, "postgres_column").block),
"{matchself{Self::Checksum(_)=>::core::result::Result::Ok(\
::ingraph::__private::field::FieldName::new(\"bit_rate_v2\")),\
Self::CoverId(_)=>::core::result::Result::Ok(\
::ingraph::__private::field::FieldName::new(\"cover_id\")),}}",
"and it is the PER-DATABASE name that is wrapped, which is what makes one resolver per \
database worth emitting — the SAME variant, two rendered names, which is the whole of what a \
storage rename is allowed to move"
);
}
#[test]
fn a_narrowed_columns_resolver_refuses_by_column_and_dialect() {
let mut model = wired();
let persist = model.persist.as_mut().expect("stored");
let taken = storage_of(&mut persist.backends[0]).columns.remove(0);
assert_eq!(taken.source.to_string(), "checksum");
let file = emission(&model);
let order_by = "VideoTrackOrderBy";
assert_eq!(
tight(&method_of(&file, order_by, "sqlite_column").block),
"{matchself{Self::Checksum(_)=>::core::result::Result::Err(\
::ingraph::__private::query::ColumnNotStored::new(\
::ingraph::__private::cursor::TermName::new(\"checksum\"),\"sqlite\")),\
Self::CoverId(_)=>::core::result::Result::Ok(\
::ingraph::__private::field::FieldName::new(\"cover_id\")),}}",
"the narrowed column's arm refuses and its neighbour is untouched"
);
assert_eq!(
tight(&method_of(&file, order_by, "postgres_column").block),
"{matchself{Self::Checksum(_)=>::core::result::Result::Ok(\
::ingraph::__private::field::FieldName::new(\"bit_rate_v2\")),\
Self::CoverId(_)=>::core::result::Result::Ok(\
::ingraph::__private::field::FieldName::new(\"cover_id\")),}}",
"and the database that KEPT the column answers with it, which is what makes the refusal the \
deployment's rather than the declaration's"
);
}
#[test]
fn an_order_by_names_its_subject_under_the_name_no_rename_moves() {
let file = emission(&wired());
assert!(
!methods_of(&file, "VideoTrackOrderBy").contains(&"identity".to_owned()),
"the fixture stores no id, so the PAGE's identity is absent — and the wire's is not"
);
let subject = wrote(&file, "ToSubjectPath").expect("the wire's identity is emitted");
assert_eq!(
impl_of(subject),
"VideoTrackOrderBy",
"on the ORDER-BY, which is the type a client's list decodes into"
);
let path = "::ingraph::__private::graphql::SubjectPath";
let name = "::ingraph::__private::cursor::TermName";
let arm = |variant: &str, field: &str| {
format!(
"Self::{variant}(_)=>{{const__INGRAPH_SUBJECT:{path}={path}::new(&[{name}::new(\
\"{field}\")]);__INGRAPH_SUBJECT}}"
)
};
let written = methods(subject);
let [method] = written.as_slice() else {
panic!("the trait has one method, not {}", written.len());
};
assert_eq!(method.sig.ident, "subject_path");
assert_eq!(
tight(&method.block),
format!(
"{{match*self{{{}{}}}}}",
arm("Checksum", "checksum"),
arm("CoverId", "cover_id")
),
"the RECORD FIELD's name in every arm — and the VARIANT is now that same name, so the arm \
reads `Self::Checksum(_) => …new(\"checksum\")` rather than pairing a storage-derived variant \
with a domain identity"
);
assert!(
tight(&method.block).contains("const__INGRAPH_SUBJECT"),
"the path is a constant, so no subject is built per request"
);
let paged = emission(&ordered());
let identity = tight(&method_of(&paged, "VideoTrackOrderBy", "identity").block);
let subject = wrote(&paged, "ToSubjectPath").expect("a paged model has both");
let subject = tight(&methods(subject)[0].block);
for field in ["media_id", "video_id", "id", "checksum", "cover_id"] {
let quoted = format!("{name}::new(\"{field}\")");
assert!(identity.contains("ed), "`identity` names {field}");
assert!(subject.contains("ed), "`subject_path` names {field}");
}
assert!(
!subject.contains("bit_rate_v2") && !subject.contains("\"bitrate\"") && !subject.contains("pk"),
"and neither database's rendering reaches the subject: {subject}"
);
let plain = emission(&whole_row());
assert_eq!(
wrote(&plain, "ToSubjectPath").map(impl_of),
Some("MediaOrderBy".to_owned()),
"the `graphql(…)` block names the type; it does not decide whether the type has an identity"
);
}
#[test]
fn an_order_by_term_carries_a_direction_for_each_stored_column_and_no_other() {
let file = emission(&wired());
let order_by = enum_named(&file, "VideoTrackOrderBy");
let direction = "::ingraph::__private::graphql::OrderDirection";
let variants: Vec<String> = order_by
.variants
.iter()
.map(|variant| format!("{}{}", variant.ident, tight(&variant.fields)))
.collect();
assert_eq!(
variants,
[
format!("Checksum({direction})"),
format!("CoverId({direction})")
],
"one single-value tuple variant per STORED column, each carrying the direction — and nothing \
for a field the declaration never persisted"
);
let accessor = method_of(&file, "VideoTrackOrderBy", "direction");
assert_eq!(returns(accessor), direction);
assert!(
is_const(accessor),
"`direction` is const beside the resolvers, so a whole term resolves in a constant"
);
assert_eq!(
tight(&accessor.block),
"{matchself{Self::Checksum(direction)|Self::CoverId(direction)=>direction,}}",
"ONE method rather than one per database: a direction is not a storage fact, so nothing about \
it is renamed by `<db>(rename)`"
);
}
#[test]
fn every_written_order_ends_with_the_id() {
let file = emission(&ordered());
let field_name = "::ingraph::__private::field::FieldName";
let sqlite = tight(&method_of(&file, "VideoTrackOrderBy", "sqlite_order_by").block);
assert!(
sqlite.contains(
"letmut__ingraph_builder=__ingraph_builder.order_by(\
__ingraph_first.sqlite_column()?,__ingraph_first.direction().is_descending(),);\
for__ingraph_termin__ingraph_rest{__ingraph_builder=__ingraph_builder.order_by(\
__ingraph_term.sqlite_column()?,__ingraph_term.direction().is_descending(),);}"
),
"{sqlite}"
);
assert!(
sqlite.contains(&format!(
"__ingraph_builder=__ingraph_builder.order_by({field_name}::new(\"id\"),false);"
)),
"the id ends the order ascending: {sqlite}"
);
for column in ["media_id", "video_id"] {
assert!(
!sqlite.contains(&format!(
"__ingraph_builder=__ingraph_builder.order_by({field_name}::new(\"{column}\"),false);"
)),
"`{column}` is a lineage column and no longer ends an order: {sqlite}"
);
}
let postgres = tight(&method_of(&file, "VideoTrackOrderBy", "postgres_order_by").block);
assert!(
postgres.contains("__ingraph_first.postgres_column()?"),
"{postgres}"
);
assert!(
postgres.contains(&format!("{field_name}::new(\"pk\")"))
&& !postgres.contains(&format!("{field_name}::new(\"id\")")),
"the tail takes THIS database's name for the id: {postgres}"
);
}
#[test]
fn an_order_over_no_terms_has_no_spelling() {
let file = emission(&ordered());
let builder = format!(
"::ingraph::__private::comparison::sql::QueryBuilder<{},{},{}>",
crate::emit::parameter("CLAUSE"),
database_parameter(),
crate::emit::parameter("HOLDER"),
);
for database in ["sqlite", "postgres"] {
let lowering = method_of(&file, "VideoTrackOrderBy", &format!("{database}_order_by"));
let parameters: Vec<String> = lowering
.sig
.inputs
.iter()
.map(|input| match input {
syn::FnArg::Typed(typed) => tight(&typed.ty),
syn::FnArg::Receiver(_) => panic!("an ordering is over terms, so it takes no self"),
})
.collect();
assert_eq!(
parameters,
["&Self", "&[Self]", builder.as_str()],
"one term, then the rest, then the statement being ordered"
);
}
}
#[test]
fn a_term_naming_the_id_is_not_appended_twice() {
let file = emission(&ordered());
let body = tight(&method_of(&file, "VideoTrackOrderBy", "sqlite_order_by").block);
assert!(
body.contains(
"if!::core::iter::once(__ingraph_first).chain(__ingraph_rest).any(|__ingraph_term|\
::core::matches!(__ingraph_term,Self::Id(_)))"
),
"the `Id` tail is guarded by a variant test over every term: {body}"
);
for variant in ["MediaId", "VideoId", "Bitrate", "CoverId"] {
assert!(
!body.contains(&format!("Self::{variant}(_)")),
"`{variant}` does not end the order and has nothing to dedupe: {body}"
);
}
}
#[test]
fn a_database_that_does_not_store_the_id_cannot_be_ordered() {
assert!(
wired().id_column_stored().is_none(),
"`wired` persists none of its key columns, the id included"
);
assert_eq!(
ordered().id_column_stored(),
Some(2),
"`ordered` prepends `media_id`, `video_id`, `id`, so the id is the row's third column — and the \
two lineage columns before it are stored without being addressed by"
);
let names = methods_of(&emission(&wired()), "VideoTrackOrderBy");
assert_eq!(
names,
[
"sqlite_column",
"postgres_column",
"mongo_column",
"direction"
],
"the resolvers and the direction survive; the walk that would need a tail does not, and \
neither does the page vocabulary that spends the same tail"
);
assert_eq!(
methods_of(&emission(&ordered()), "VideoTrackOrderBy"),
[
"sqlite_column",
"postgres_column",
"mongo_column",
"direction",
"identity",
"sqlite_term",
"postgres_term",
"complete",
"sqlite_order_by",
"postgres_order_by"
],
"one lowering per SQL database — the clause machine it walks is the SQL family's, and how a \
mongo `find` takes a sort is unsettled"
);
}
#[test]
fn a_mongo_only_record_with_a_wire_face_still_names_nothing_of_the_sql_family() {
let mut model = ordered();
model
.persist
.as_mut()
.expect("`ordered` stores rows")
.backends
.retain(|database| !database.kind().is_sql());
let file = emission(&model);
assert_eq!(
methods_of(&file, "VideoTrackOrderBy"),
["mongo_column", "direction"],
"the resolver and the direction are all a mongo order-by has"
);
let rendered = tight(&file);
assert!(
!rendered.contains("__private::sqlx"),
"a mongo-only expansion reaches sqlx: {rendered}"
);
}
#[test]
fn only_the_databases_with_a_backend_can_host_a_framework_table() {
use crate::model::{DatabaseKind, ProgressHost};
for kind in DatabaseKind::ALL {
let hosts = matches!(kind, DatabaseKind::Sqlite | DatabaseKind::Postgres);
assert_eq!(
ProgressHost::of(kind).map(|host| host.kind()),
hosts.then_some(kind),
"`store/progress/` ships a ledger for sqlite and postgres alone: {}",
kind.as_str()
);
assert_eq!(ProgressHost::hosts(kind), ProgressHost::of(kind).is_some());
}
}
#[test]
fn the_query_face_is_emitted_per_sql_database_and_never_for_mongo() {
let mut model = whole_row();
let record = model.record.clone();
let columns = model
.persist
.as_ref()
.expect("`whole_row` stores rows")
.backends[0]
.columns()
.to_vec();
model
.persist
.as_mut()
.expect("`whole_row` stores rows")
.backends
.push(stored(&record, DatabaseKind::Mongo, columns));
let named = methods_of(&emission(&model), "Media");
for wanted in ["find_sqlite", "find_sqlite_snapshot", "get_sqlite"] {
assert!(
named.iter().any(|method| method == wanted),
"a SQL database gets `{wanted}`: {named:?}"
);
}
for refused in ["find_mongo", "find_mongo_snapshot", "get_mongo"] {
assert!(
!named.iter().any(|method| method == refused),
"and a mongo database gets no `{refused}`: {named:?}"
);
}
assert!(
!declared_types(&emission(&model))
.iter()
.any(|declared| declared == "MediaMongoCursor"),
"nor a cursor value, which is a page's and a page is the SQL family's"
);
}
#[test]
fn a_row_that_cannot_become_a_record_gets_no_query_face() {
let model = ordered();
assert!(
model.queryable().is_empty(),
"a partial row with no declared conversion cannot raise a record"
);
let file = emission(&model);
let named = methods_of(&file, "VideoTrack");
assert!(
!named
.iter()
.any(|method| method.starts_with("find_") || method.starts_with("get_")),
"so the record gets no entry point: {named:?}"
);
assert!(
!declared_types(&file)
.iter()
.any(|declared| declared.ends_with("Cursor")),
"and no cursor value either"
);
}
fn referring() -> RecordModel {
let mut model = model("VideoTrack", &["media_id"], "id");
model.fields = [
("media_id", ty("MediaId"), "Media", Through::Value),
("video_id", ty("VideoId"), "Video", Through::Value),
("replaces", ty("VideoId"), "Video", Through::Value),
("scenes", generic("Vec", "SceneId"), "Scene", Through::Held),
]
.into_iter()
.map(|(name, ty, target, through)| Field {
column: column_of(name, ty),
identity: false,
marker: None,
sortable: false,
indexed: false,
skip: None,
docs: Vec::new(),
condition: Condition::always(),
build: Build::default(),
reference: Some(Reference {
target: syn::parse_str(target).expect("a type path"),
through,
}),
})
.collect();
model.derived = vec![
Derived {
name: ident("clips"),
source: syn::parse_str("Clip").expect("a type path"),
field: None,
},
Derived {
name: ident("takes"),
source: syn::parse_str("Take").expect("a type path"),
field: Some(syn::parse_quote!("track_id")),
},
];
model
}
#[test]
fn a_ref_states_the_id_equation_through_the_declared_projection() {
let emitted = tight(referring().relations());
assert!(
emitted.contains("refers_to::<MediaId,Media>"),
"a bare field's own type IS the referring value: {emitted}"
);
assert!(
emitted.contains(
"refers_to::<<Vec<SceneId>as::ingraph::__private::state::State<::ingraph::__private::state::\
Extracted<::ingraph::__private::state::Inner>>>::Output,Scene>"
),
"and a collection's is what the TYPE says it holds: {emitted}"
);
}
#[test]
fn the_pairing_is_one_impl_per_target() {
let file = emission(&referring());
let pairings: Vec<String> = trait_impls(&file)
.into_iter()
.filter(|(_, path)| tight(path).contains("transform::Related"))
.map(|(_, path)| tight(path))
.collect();
assert_eq!(
pairings.len(),
3,
"one per target, not one per field: {pairings:?}"
);
let fields = |target: &str| {
trait_impls(&file)
.into_iter()
.find(|(_, path)| tight(path).ends_with(&format!("Related<{target}>")))
.map(|(item, _)| {
item
.items
.iter()
.find_map(|item| match item {
syn::ImplItem::Type(item) => Some(tight(&item.ty)),
_ => None,
})
.expect("the pairing binds `Fields`")
})
.expect("a pairing at that target")
};
assert_eq!(
fields("Video"),
"(VideoTrackVideoIdRef,VideoTrackReplacesRef,)",
"two fields at one target are two members of one list"
);
assert_eq!(fields("Media"), "(VideoTrackMediaIdRef,)");
}
#[test]
fn the_pairing_carries_the_referring_columns() {
let emitted = tight(referring().relations());
assert!(
emitted.contains(
"constCOLUMNS:&'static[&'static::ingraph::__private::field::FieldName]=&[::ingraph::\
__private::field::FieldName::new(\"video_id\"),::ingraph::__private::field::FieldName::new(\
\"replaces\")]"
),
"{emitted}"
);
}
#[test]
fn a_membership_emits_the_evidence_an_interface_asserts() {
let mut model = referring();
model.implements = vec![
syn::parse_str("Media").expect("a type path"),
syn::parse_str("media::Playable").expect("a type path"),
];
let emitted = tight(model.relations());
assert!(
emitted.contains("impl::ingraph::__private::transform::Implements<Media>forVideoTrack{}"),
"{emitted}"
);
assert!(
emitted
.contains("impl::ingraph::__private::transform::Implements<media::Playable>forVideoTrack{}"),
"an alias in the path is transparent: nothing here resolves it: {emitted}"
);
assert!(
!declared_types(&emission(&model))
.iter()
.any(|declared| declared == "Media"),
"a membership declares no type"
);
}
#[test]
fn a_membership_the_declaration_never_named_is_unauthorised() {
let mut model = referring();
model.implements = vec![syn::parse_str("Media").expect("a type path")];
let file = emission(&model);
assert_eq!(
unauthorised_framework_impls(&model, &file),
Vec::<String>::new()
);
let mut undeclared = referring();
undeclared.implements = Vec::new();
assert_eq!(
unauthorised_framework_impls(&undeclared, &file),
["::ingraph::__private::transform::Implements<Media> for VideoTrack"]
);
}
#[test]
fn a_reverse_position_emits_an_audit_and_no_type() {
let model = referring();
let emitted = tight(model.relations());
assert!(
emitted.contains("one_field_points_back::<Clip,VideoTrack>"),
"the shorthand asks the evidence to pick the one field: {emitted}"
);
assert!(
emitted.contains(
"refers_through(<Takeas::ingraph::__private::transform::Related<VideoTrack>>\
::COLUMNS,\"track_id\")"
),
"and the full form names it: {emitted}"
);
assert!(
!declared_types(&emission(&model))
.iter()
.any(|declared| declared == "clips" || declared == "takes"),
"no storage, no field, no lie"
);
}
#[test]
fn the_reference_artifacts_stay_inside_the_const() {
let file = emission(&referring());
assert!(
!names(&file).iter().any(|name| name.ends_with("Ref")),
"nothing at top level: {:?}",
names(&file)
);
let inside: Vec<String> = declared_types(&file)
.into_iter()
.filter(|declared| declared.ends_with("Ref"))
.collect();
assert_eq!(
inside,
[
"VideoTrackMediaIdRef",
"VideoTrackVideoIdRef",
"VideoTrackReplacesRef",
"VideoTrackScenesRef",
],
"one per referring field, named after it"
);
}
#[test]
fn a_reference_artifact_seals_its_own_construction() {
let file = emission(&referring());
let artifacts: Vec<&syn::ItemStruct> = all_items(&file)
.into_iter()
.filter_map(|item| match item {
syn::Item::Struct(item) if item.ident.to_string().ends_with("Ref") => Some(item),
_ => None,
})
.collect();
assert!(
!artifacts.is_empty(),
"the walk found no artifact to seal, so the rest of this would pass vacuously"
);
for item in artifacts {
let syn::Fields::Unnamed(sealed) = &item.fields else {
panic!("`{}` carries no sealing field: {}", item.ident, tight(item));
};
assert_eq!(
sealed.unnamed.len(),
1,
"`{}` is sealed by ONE field: {}",
item.ident,
tight(item)
);
let field = sealed.unnamed.first().expect("the sealing field");
assert_eq!(
tight(&field.ty),
"()",
"`{}` seals with the unit",
item.ident
);
assert!(
matches!(field.vis, syn::Visibility::Inherited),
"`{}`'s field is PRIVATE — a visible one would mint the value it exists to refuse",
item.ident
);
}
}
#[test]
fn a_relation_declares_only_authorised_impls() {
let model = referring();
let file = emission(&model);
assert!(
unauthorised_framework_impls(&model, &file).is_empty(),
"{:?}",
unauthorised_framework_impls(&model, &file)
);
}
#[test]
fn the_order_by_carries_a_oneof_wire_face_and_the_key_argument_a_product_one() {
let file = emission(&wired());
let faces: Vec<String> = trait_impls(&file)
.into_iter()
.filter(|(_, path)| tight(path).contains("async_graphql"))
.map(|(item, path)| format!("{} for {}", tight(path), impl_of(item)))
.collect();
assert_eq!(
faces,
[
"::ingraph::__private::async_graphql::InputType for VideoTrackKeyInput",
"::ingraph::__private::async_graphql::InputObjectType for VideoTrackKeyInput",
"::ingraph::__private::async_graphql::InputType for VideoTrackOrderBy",
"::ingraph::__private::async_graphql::InputObjectType for VideoTrackOrderBy",
"::ingraph::__private::async_graphql::OneofObjectType for VideoTrackOrderBy",
],
"the two input faces, and the choice marker on the order-by alone"
);
}
#[test]
fn a_root_key_crosses_inward_as_its_id_and_declares_no_argument_object() {
let mut model = media();
let base = model.record.clone();
model.graphql = Some(Graphql {
backends: vec![GraphqlBackend::AsyncGraphql(AsyncGraphql {
skipped: Vec::new(),
attrs: proc_macro2::TokenStream::new(),
fields: Vec::new(),
})],
input: RustSafeName::from_ident(&default_input_name(&base)),
output: RustSafeName::from_ident(&default_output_name(&base)),
key_output: RustSafeName::from_ident(&default_key_output_name(&base)),
key_object: None,
key_argument: None,
filter: RustSafeName::from_ident(&default_filter_name(&base)),
plural: None,
connection: None,
edge: None,
skipped: Vec::new(),
});
assert!(
!model.key.compound(),
"`{}` is the ROOT fixture this reading needs",
model.record
);
let named: Vec<String> = model
.emitted_types()
.iter()
.map(|declared| declared.name.to_string())
.collect();
assert!(
!named.iter().any(|name| name.ends_with("KeyInput")),
"a root enumerated an argument object: {named:?}"
);
let emitted = model.emit().to_string();
assert!(
!emitted.contains("KeyInput"),
"a root emitted an argument object"
);
assert!(
emitted.contains("ToGraphqlInput for"),
"a root emitted no inward crossing at all"
);
}
#[test]
fn an_order_by_subject_takes_the_name_the_filter_gave_its_column() {
let emitted = wired().emit().to_string().replace(' ', "");
assert!(
emitted.contains(r#"String::from("bitRate")"#),
"the subject is named as the filter names it"
);
assert!(
!emitted.contains(r#"String::from("checksum")"#),
"and not by the record field's own name"
);
assert!(emitted.contains("oneof:true"), "the `@oneOf` flag is set");
}
#[test]
fn the_wire_face_writes_no_description_anywhere() {
let emitted = wired().emit().to_string().replace(' ', "");
assert!(
emitted.contains("description:::core::option::Option::None"),
"the entry writes the `None` explicitly"
);
assert!(
!emitted.contains("description:::core::option::Option::Some"),
"and never a `Some`"
);
}
#[test]
fn every_wire_method_wears_the_prefix_and_spells_its_own_client_name() {
fn face(file: &syn::File, owner: &str) -> Vec<(String, String)> {
inherent(file)
.into_iter()
.filter(|item| owner_of(item) == owner)
.flat_map(methods)
.filter(|method| method.sig.asyncness.is_some())
.map(|method| {
let attrs: Vec<String> = method.attrs.iter().map(tight).collect();
assert_eq!(
attrs.len(),
1,
"ONE attribute on `{}`, and it is the client's name — a doc attribute here would publish \
prose, and a missing name would publish the prefix: {attrs:?}",
method.sig.ident
);
(
method.sig.ident.to_string(),
attrs.into_iter().next().expect("just counted"),
)
})
.collect()
}
let mut model = wired();
match &mut model.graphql.as_mut().expect("wired").backends[0] {
GraphqlBackend::AsyncGraphql(backend) => {
backend.fields[1].output.name = RustSafeName::from_ident(&ident("cover_id"));
}
}
let file = emission(&model);
assert_eq!(
face(&file, "VideoTrackGraphqlOutput"),
[
(
"__async_graphql_id".to_owned(),
r#"#[graphql(name="id")]"#.to_owned()
),
(
"__async_graphql_key".to_owned(),
r#"#[graphql(name="key")]"#.to_owned()
),
(
"__async_graphql_checksum".to_owned(),
r#"#[graphql(name="bitRate")]"#.to_owned()
),
(
"__async_graphql_cover_id".to_owned(),
r#"#[graphql(name="coverId")]"#.to_owned()
),
],
"the OUTPUT object: prefixed idents, and the wire names the library used to derive"
);
assert_eq!(
face(&file, "VideoTrackKeyOutput"),
[
(
"__async_graphql_media_id".to_owned(),
r#"#[graphql(name="mediaId")]"#.to_owned()
),
(
"__async_graphql_video_id".to_owned(),
r#"#[graphql(name="videoId")]"#.to_owned()
),
(
"__async_graphql_id".to_owned(),
r#"#[graphql(name="id")]"#.to_owned()
),
],
"the ADDRESS object: no word can reach a key column, so every name here is the computed one"
);
let accessors = methods_of(&file, "VideoTrackGraphqlOutput");
assert!(
accessors.contains(&"cover_id_ref".to_owned())
&& !accessors.contains(&"__async_graphql_cover_id_ref".to_owned()),
"the prefix is the WIRE face's and reaches no accessor: {accessors:?}"
);
}
#[test]
fn the_wire_face_is_emitted_inside_the_binding_gate() {
let emitted = wired().emit().to_string().replace(' ', "");
assert!(emitted.contains("::ingraph::__private::gate::if_async_graphql!"));
}
#[test]
fn a_record_with_nothing_to_order_by_gets_no_wire_face() {
let mut model = wired();
model.persist = None;
let emitted = model.emit().to_string().replace(' ', "");
assert!(
!emitted.contains("OneofObjectType"),
"a record that stores nothing has no order to write"
);
assert!(
emitted.contains("if_async_graphql"),
"and the output faces are there anyway — an address is a field, so the object is a legal type"
);
}
fn attributes(emitted: &str) -> Vec<String> {
let bytes = emitted.as_bytes();
let mut found = Vec::new();
let mut at = 0;
while let Some(hit) = emitted[at..].find("#[") {
let open = at + hit + 1;
let mut depth = 0usize;
let mut end = None;
for (step, byte) in bytes[open..].iter().enumerate() {
match byte {
b'[' => depth += 1,
b']' => {
depth -= 1;
if depth == 0 {
end = Some(open + step);
break;
}
}
_ => {}
}
}
let Some(end) = end else { break };
found.push(emitted[open + 1..end].to_owned());
at = end + 1;
}
found
}
fn attributes_missing_the_crate_key(emitted: &str) -> Vec<String> {
const SHELF: &str = "::ingraph::__private::async_graphql";
attributes(emitted)
.into_iter()
.filter(|attribute| attribute.contains("async_graphql") && !attribute.starts_with("doc"))
.filter(|attribute| {
!attribute.starts_with(SHELF) || !attribute.contains(&format!(r#"crate="{SHELF}""#))
})
.collect()
}
#[test]
fn no_emitted_async_graphql_attribute_is_missing_the_crate_key() {
const SHELF: &str = "::ingraph::__private::async_graphql";
let compliant = format!(r#"#[{SHELF}::Object(crate="{SHELF}")]structX;"#);
assert!(
attributes_missing_the_crate_key(&compliant).is_empty(),
"the shelf path AND the key is what compliance looks like"
);
assert_eq!(
attributes_missing_the_crate_key("#[::async_graphql::Object]structX;").len(),
1,
"a bare path with no key is caught"
);
assert_eq!(
attributes_missing_the_crate_key(&format!(r#"#[{SHELF}::Object]structX;"#)).len(),
1,
"the shelf path alone is not enough — the expansion still needs the key"
);
assert_eq!(
attributes_missing_the_crate_key(&format!(
r#"#[::async_graphql::Object(crate="{SHELF}")]f();"#
))
.len(),
1,
"and the key alone is not enough — the ATTRIBUTE itself has to resolve"
);
assert!(
attributes_missing_the_crate_key("#[serde(with=\"x\")]#[doc=\"async_graphql\"]structX;")
.is_empty(),
"a doc mentioning the crate is not an attribute of it"
);
for (label, model) in [("wired", wired()), ("referring", referring())] {
let emitted = model.emit().to_string().replace(' ', "");
assert!(
attributes_missing_the_crate_key(&emitted).is_empty(),
"{label}: {:?}",
attributes_missing_the_crate_key(&emitted)
);
}
let face = crate::enumeration::EnumModel {
krate: syn::parse_quote!(::ingraph),
vis: syn::parse_quote!(pub),
name: syn::parse_quote!(Codec),
width: None,
variants: vec![crate::enumeration::EnumVariant {
ident: syn::parse_quote!(H264),
rename: None,
names: std::collections::BTreeMap::new(),
upstream: None,
escape: None,
carrier: None,
}],
forms: std::collections::BTreeMap::new(),
wire_name: None,
error: None,
remote: None,
}
.emit()
.to_string()
.replace(' ', "");
assert!(
attributes_missing_the_crate_key(&face).is_empty(),
"the vocabulary's emission: {:?}",
attributes_missing_the_crate_key(&face)
);
}
fn fused_and_forked() -> RecordModel {
let mut model = model("Describe", &["media_id"], "id");
model.kind = NodeKind::Operator;
model.subscriptions = Some(Subscription {
upstreams: vec![
upstream("media::Frame", true, None),
upstream("asr::Segment", true, None),
upstream("media::Scene", false, None),
upstream("vision::Detector", false, Some("Boxes")),
],
});
model.products = Some(Products {
products: vec![product("Caption"), product("Summary")],
});
model
}
fn upstream(node: &str, keyed: bool, out: Option<&str>) -> Upstream {
let node: syn::Path = syn::parse_str(node).expect("a path");
let out = out.map(ident);
let variant = out.clone().unwrap_or_else(|| {
node
.segments
.last()
.expect("a path has a last segment")
.ident
.clone()
});
Upstream {
node,
keyed,
out,
variant,
channel: None,
changes: None,
notify: false,
}
}
fn product(ty: &str) -> Product {
let ty: syn::Path = syn::parse_str(ty).expect("a path");
let variant = ty
.segments
.last()
.expect("a path has a last segment")
.ident
.clone();
Product { ty, variant }
}
#[test]
fn the_fan_in_carries_the_group_as_one_variant_and_the_straights_beside_it() {
let model = fused_and_forked();
let file = emission(&model);
let fan_in = enum_named(&file, &default_in_name(&model.record).to_string());
assert_eq!(
fan_in
.variants
.iter()
.map(|variant| variant.ident.to_string())
.collect::<Vec<_>>(),
[crate::emit::PAIRED, "Scene", "Boxes"],
"the group takes the first keyed entry's place, and each straight takes its own"
);
let paired = &fan_in.variants[0];
assert_eq!(
paired.fields.len(),
2,
"one payload per member of the group"
);
assert_eq!(
paired
.fields
.iter()
.map(|field| tight(&field.ty))
.collect::<Vec<_>>(),
[
"<media::Frameas::ingraph::__private::operator::Emits>::Out",
"<asr::Segmentas::ingraph::__private::operator::Emits>::Out",
],
"each payload is the upstream's OWN statement of what it emits"
);
}
#[test]
fn a_selected_product_is_projected_through_the_upstreams_vocabulary() {
let model = fused_and_forked();
let file = emission(&model);
let fan_in = enum_named(&file, &default_in_name(&model.record).to_string());
let boxes = fan_in
.variants
.iter()
.find(|variant| variant.ident == "Boxes")
.expect("the selected edge");
assert_eq!(
tight(&boxes.fields.iter().next().expect("one payload").ty),
"<vision::Detectoras::ingraph::__private::operator::Emits<{vision::DetectorOutKind::Boxesasusize}>>::Out",
);
}
#[test]
fn a_multi_product_node_emits_its_sum_its_vocabulary_and_its_downstream() {
let model = fused_and_forked();
let file = emission(&model);
let record = &model.record;
let out = enum_named(&file, &default_out_name(record).to_string());
assert_eq!(
out
.variants
.iter()
.map(|variant| (variant.ident.to_string(), variant.fields.len()))
.collect::<Vec<_>>(),
[("Caption".to_owned(), 1), ("Summary".to_owned(), 1)],
);
let kind = enum_named(&file, &default_out_kind_name(record).to_string());
assert!(
kind
.variants
.iter()
.all(|variant| variant.fields.is_empty()),
"the vocabulary carries identities and no payloads"
);
let downstream = structs(&file)
.into_iter()
.find(|item| item.ident == default_downstream_name(record))
.expect("the downstream is emitted");
assert_eq!(
downstream
.fields
.iter()
.map(|field| tight(&field.ty))
.collect::<Vec<_>>(),
[
"::std::vec::Vec<::ingraph::__private::drive::Outbox<::ingraph::__private::drive::ItemId,Caption>>",
"::std::vec::Vec<::ingraph::__private::drive::Outbox<::ingraph::__private::drive::ItemId,Summary>>",
],
"one out-edge LIST per product — several subscribers to one product is the ordinary road — and \
a list's emptiness IS the connection state"
);
}
#[test]
fn the_routing_impl_is_on_the_downstream_at_the_nodes_own_sum() {
let model = fused_and_forked();
let file = emission(&model);
let routing: Vec<String> = trait_impls(&file)
.into_iter()
.filter(|(_, path)| tight(path).contains("drive::Sink"))
.map(|(item, path)| format!("{} for {}", tight(path), impl_of(item)))
.collect();
assert_eq!(
routing,
[format!(
"::ingraph::__private::drive::Sink<{}> for {}",
default_out_name(&model.record),
default_downstream_name(&model.record),
)],
"one impl, on the downstream the node declares, at the sum it declares beside it"
);
}
#[test]
fn several_products_are_stated_one_row_apiece() {
let file = emission(&fused_and_forked());
let rows: Vec<String> = trait_impls(&file)
.into_iter()
.filter(|(_, path)| tight(path).contains("operator::Emits"))
.map(|(item, path)| {
let associated = item
.items
.iter()
.filter_map(|item| match item {
syn::ImplItem::Type(ty) => Some(tight(&ty.ty)),
_ => None,
})
.collect::<Vec<_>>()
.join(",");
format!("{} = {associated}", tight(path))
})
.collect();
assert_eq!(
rows,
[
"::ingraph::__private::operator::Emits<0usize> = Caption",
"::ingraph::__private::operator::Emits<1usize> = Summary",
],
);
assert!(
!trait_impls(&file)
.iter()
.any(|(_, path)| tight(path).contains("SoleProduct")),
"a node that emits several carries no sole-product marker"
);
}
#[test]
fn one_product_is_stated_as_the_declared_struct_and_carries_the_marker() {
let file = emission(&video_track());
let rows: Vec<String> = trait_impls(&file)
.into_iter()
.filter(|(_, path)| tight(path).contains("operator::"))
.map(|(item, path)| format!("{} for {}", tight(path), impl_of(item)))
.collect();
assert_eq!(
rows,
[
"::ingraph::__private::operator::Emits for VideoTrack",
"::ingraph::__private::operator::SoleProduct for VideoTrack",
],
);
assert!(
structs(&file)
.iter()
.all(|item| item.ident != default_downstream_name(&ident("VideoTrack"))),
"and it declares no downstream of its own — the framework's holder is its shape"
);
}
#[test]
fn an_unselected_subscription_discharges_the_one_product_audit() {
let emitted = tight(fused_and_forked().emit());
assert!(
emitted.contains("__ig_takes_one_product"),
"the audit is emitted"
);
for upstream in ["media::Frame", "asr::Segment", "media::Scene"] {
assert!(
emitted.contains(&format!(
"__ig_takes_one_product::<{}>",
upstream.replace(' ', "")
)),
"`{upstream}` named no product, so it must emit one"
);
}
assert!(
!emitted.contains("__ig_takes_one_product::<vision::Detector>"),
"the entry that named a product is audited by its own projection"
);
}
#[test]
fn a_plain_node_gains_no_topology_types() {
let before = names(&emission(&video_track()));
assert_eq!(
before,
["TrackAddress", "TrackScope"],
"the key and the lineage, and no fan-in, sum, vocabulary or downstream beside them"
);
}