use quote::ToTokens as _;
use super::{FieldsModel, FragmentField};
use crate::model::{Column, Projection};
fn ident(name: &str) -> syn::Ident {
syn::Ident::new(name, proc_macro2::Span::call_site())
}
fn column(name: &str, ty: &str, project: Projection) -> FragmentField {
FragmentField {
column: Column {
name: ident(name),
source: ident(name),
ty: syn::parse_str(ty).expect("a type"),
project,
},
docs: Vec::new(),
build: crate::construct::Build::default(),
flatten: false,
condition: crate::model::Condition::always(),
skip: None,
stored_name: None,
wire_name: None,
derived: Vec::new(),
write: None,
read: None,
}
}
fn deriving(name: &str, ty: &str, column: &str, from: &str, derived: &str) -> FragmentField {
FragmentField {
derived: vec![super::Derived {
column: crate::name::RustSafeName::new(column, proc_macro2::Span::call_site()),
from: syn::parse_str(from).expect("a path"),
ty: syn::parse_str(derived).expect("a type"),
}],
..self::column(name, ty, Projection::Copied)
}
}
fn writing(name: &str, ty: &str, write: &str) -> FragmentField {
FragmentField {
write: Some(syn::parse_str(write).expect("a path")),
..column(name, ty, Projection::Borrowed)
}
}
fn flattened(name: &str, ty: &str) -> FragmentField {
FragmentField {
flatten: true,
..column(name, ty, Projection::Borrowed)
}
}
fn dimensions() -> FieldsModel {
FieldsModel {
fragment: ident("Dimensions"),
vis: syn::Visibility::Public(syn::token::Pub::default()),
krate: syn::parse_quote!(::ingraph),
remote: None,
fields: vec![
column("width", "u32", Projection::Copied),
column("label", "String", Projection::Borrowed),
],
construction: crate::construct::Construction::default(),
cursor: None,
filter: None,
delegates: Vec::new(),
record: Some(super::RecordHost {
databases: Vec::new(),
write: None,
read: None,
}),
entity: true,
wire: Some(super::WireFace {
object: None,
filter: None,
}),
}
}
fn built(kind: crate::model::DatabaseKind) -> super::BuiltFor {
super::BuiltFor {
kind,
comparison: None,
cursor: None,
}
}
fn wrapped() -> FieldsModel {
FieldsModel {
remote: Some(syn::parse_quote!(upstream::Dimensions)),
..dimensions()
}
}
fn emission(model: &FieldsModel) -> syn::File {
syn::parse2(model.emit()).expect("the emission is a parsable file")
}
fn items(file: &syn::File) -> Vec<&syn::Item> {
let mut found = Vec::new();
for item in &file.items {
found.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 {
found.push(inner);
}
}
}
}
found
}
fn bound(file: &syn::File) -> Vec<String> {
items(file)
.into_iter()
.filter_map(|item| match item {
syn::Item::Impl(item) => Some(item),
_ => None,
})
.filter_map(|item| {
let (path, _) = item.trait_.as_ref()?;
Some(
format!(
"{} for {}",
path.to_token_stream(),
item.self_ty.to_token_stream()
)
.replace(' ', ""),
)
})
.collect()
}
#[test]
fn the_traits_are_the_width_the_markers_and_the_comparison() {
let file = emission(&dimensions());
let bound = bound(&file);
for expected in [
"::ingraph::__private::column::ColumnKindforDimensions",
"::ingraph::__private::marker::CompositeFilterMarkerforDimensions",
"::ingraph::__private::marker::DefaultMarkerforDimensions",
"::ingraph::__private::graphql::ToGraphqlOutputforDimensions",
"::ingraph::__private::graphql::GraphqlFilterforDimensionsFilter",
"::ingraph::__private::graphql::GraphqlFilterforDimensionsColumnFilter",
] {
assert!(bound.iter().any(|row| row == expected), "{bound:?}");
}
for face in ["ComplexComparison", "CompositeComparison"] {
assert!(
bound
.iter()
.any(|row| row.contains(face) && row.contains("forDimensionsComparison")),
"the comparison wears {face}: {bound:?}"
);
}
for face in [
"::core::default::DefaultforDimensionsComparison<__INGRAPH_DB__>",
"::ingraph::__private::comparison::TryFromFilter<DimensionsColumnFilter>\
forDimensionsComparison<__INGRAPH_DB__>",
] {
assert!(
bound.iter().any(|row| row == face),
"the bare word's pair is dialect-generic: {bound:?}"
);
}
assert!(
bound
.iter()
.any(|row| row.contains("ToDatabaseComparison<Dimensions")
&& row.contains("forDimensionsColumnFilter")),
"the map row crosses the STORED filter into the comparison: {bound:?}"
);
assert!(
!bound
.iter()
.any(|row| row.contains("ToDatabaseComparison<Dimensions")
&& row.contains("forDimensionsFilter")),
"and the full face states no lowering: {bound:?}"
);
for absent in ["Identifiable", "Transformer", "Graphql", "Record"] {
assert!(
!bound.iter().any(|row| row.starts_with(absent)),
"a fragment binds no {absent}: {bound:?}"
);
}
assert!(
bound
.iter()
.any(|row| row == "::ingraph::__private::column::StoredAs<__INGRAPH_DB__>forDimensions"),
"the declared word is stated: {bound:?}"
);
assert!(
bound
.iter()
.any(|row| row == "::ingraph::__private::column::DeclaredLeavesforDimensions"),
"the fragment says its columns mean the sequence it declares them in: {bound:?}"
);
assert!(
bound
.iter()
.any(|row| row == "::ingraph::__private::column::ColumnEqforDimensions"),
"the fragment says when two of it are one column value: {bound:?}"
);
assert_eq!(bound.len(), 14, "and nothing else: {bound:?}");
}
#[test]
fn the_object_is_gated_and_the_crossing_is_not() {
let rendered = prettyplease::unparse(&emission(&dimensions())).replace(' ', "");
assert!(
rendered.contains("gate::if_async_graphql!"),
"the object rides the gate: {rendered}"
);
assert!(
rendered.contains("async_graphql::Object"),
"and what it carries is the object: {rendered}"
);
assert!(rendered.contains(r#"graphql(name="width")"#), "{rendered}");
assert_eq!(
rendered.matches("gate::if_async_graphql!").count(),
3,
"one input face per predicate, and the object: {rendered}"
);
let (before, _) = rendered
.rsplit_once("gate::if_async_graphql!")
.expect("the gate");
assert!(
before.contains("ToGraphqlOutputforDimensions"),
"the crossing is ungated: {before}"
);
assert!(
before.contains("GraphqlFilterforDimensionsFilter"),
"and so is the emptiness answer: {before}"
);
}
#[test]
fn the_types_it_mints_are_the_filter_and_the_comparison() {
let file = emission(&dimensions());
let minted: Vec<String> = 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();
assert_eq!(
minted,
[
"DimensionsFilter",
"DimensionsColumnFilter",
"DimensionsComparison"
]
);
let top: Vec<String> = file
.items
.iter()
.filter_map(|item| match item {
syn::Item::Struct(item) => Some(item.ident.to_string()),
_ => None,
})
.collect();
assert_eq!(
top,
[
"DimensionsFilter",
"DimensionsColumnFilter",
"DimensionsComparison"
]
);
}
#[test]
fn every_field_carries_its_mutators() {
assert_eq!(
own_methods(&emission(&dimensions())),
[
"width",
"width_ref",
"set_width",
"with_width",
"label_ref",
"set_label",
"with_label",
],
"the copy field's extra accessor, and both mutators on each"
);
}
fn own_methods(file: &syn::File) -> Vec<String> {
items(file)
.into_iter()
.filter_map(|item| match item {
syn::Item::Impl(item)
if item.trait_.is_none() && item.self_ty.to_token_stream().to_string() == "Dimensions" =>
{
Some(item)
}
_ => None,
})
.flat_map(|item| &item.items)
.filter_map(|item| match item {
syn::ImplItem::Fn(method) => Some(method.sig.ident.to_string()),
_ => None,
})
.collect()
}
#[test]
fn the_walk_names_exactly_the_methods_the_emission_declares() {
let model = dimensions();
let walked: Vec<String> = model
.emitted_methods()
.iter()
.map(|emitted| emitted.name.to_string())
.collect();
assert_eq!(
walked,
[
"width",
"width_ref",
"set_width",
"with_width",
"label_ref",
"set_label",
"with_label",
]
);
}
#[test]
fn the_methods_take_the_declarations_own_visibility() {
let mut model = dimensions();
model.vis = syn::Visibility::Inherited;
let rendered = prettyplease::unparse(&emission(&model));
assert!(
!rendered.contains("pub "),
"a private value's methods are private: {rendered}"
);
assert!(
prettyplease::unparse(&emission(&dimensions())).contains("pub const fn width("),
"and a public one's are public"
);
}
#[test]
fn a_rewrite_keeps_every_face_and_adds_the_reference_family() {
let bound = bound(&emission(&wrapped()));
for face in [
"::ingraph::__private::column::ColumnKindforDimensions",
"::ingraph::__private::column::ColumnEqforDimensions",
"::ingraph::__private::marker::CompositeFilterMarkerforDimensions",
"::ingraph::__private::marker::DefaultMarkerforDimensions",
"::ingraph::__private::graphql::ToGraphqlOutputforDimensions",
"::ingraph::__private::graphql::GraphqlFilterforDimensionsFilter",
"::ingraph::__private::graphql::GraphqlFilterforDimensionsColumnFilter",
] {
assert!(bound.iter().any(|row| row == face), "{bound:?}");
}
for wrapper in [
"::core::convert::AsRef<upstream::Dimensions>forDimensions",
"::core::convert::AsMut<upstream::Dimensions>forDimensions",
"::core::ops::DerefforDimensions",
"::core::ops::DerefMutforDimensions",
"::core::borrow::Borrow<upstream::Dimensions>forDimensions",
"::core::borrow::BorrowMut<upstream::Dimensions>forDimensions",
"::core::convert::From<upstream::Dimensions>forDimensions",
"::core::convert::From<Dimensions>forupstream::Dimensions",
] {
assert!(bound.iter().any(|row| row == wrapper), "{bound:?}");
}
assert!(
bound
.iter()
.any(|row| row.starts_with("__IngraphRemoteBridge")),
"the crossing marker is declared: {bound:?}"
);
for face in [
"::core::default::DefaultforDimensionsComparison<__INGRAPH_DB__>",
"::ingraph::__private::comparison::TryFromFilter<DimensionsColumnFilter>\
forDimensionsComparison<__INGRAPH_DB__>",
] {
assert!(bound.iter().any(|row| row == face), "{bound:?}");
}
for absent in ["Identifiable", "Transformer", "Graphql", "Record"] {
assert!(
!bound.iter().any(|row| row.starts_with(absent)),
"a wrapping fragment binds no {absent}: {bound:?}"
);
}
assert_eq!(bound.len(), 23, "and nothing else: {bound:?}");
}
#[test]
fn a_rewrite_reads_every_field_by_crossing_and_nothing_else() {
let file = emission(&wrapped());
assert_eq!(
own_methods(&file),
["width", "label"],
"one reader per manifest field, in declared order"
);
let rendered = prettyplease::unparse(&file);
assert!(
rendered.contains("pub fn width(&self) -> u32 {\n __ingraph_cross(self.0.width())"),
"the read is the remote's own accessor, crossed: {rendered}"
);
assert!(
!rendered.contains("pub const fn width("),
"a foreign accessor is not this emission's to declare `const`: {rendered}"
);
}
#[test]
fn a_manifest_fields_docs_ride_its_reader() {
let mut model = wrapped();
model.fields[1].docs = vec![syn::parse_quote!(#[doc = " The label, as the upstream spells it."])];
let rendered = prettyplease::unparse(&emission(&model));
assert!(
rendered.contains("The label, as the upstream spells it."),
"the sentence the author wrote survives the item that carried it: {rendered}"
);
}
#[test]
fn the_wrapped_wire_arm_holds_its_value_and_crosses_out_of_it() {
let dense = |model: &FieldsModel| {
prettyplease::unparse(&emission(model))
.split_whitespace()
.collect::<String>()
};
let held = dense(&dimensions());
assert!(
held.contains("asyncfn__async_graphql_label(&self)-><Stringas"),
"a held field crosses: {held}"
);
let wrapped = dense(&wrapped());
assert!(
wrapped.contains(
"asyncfn__async_graphql_label(&self)->::ingraph::__private::graphql::Crossed<String>{::\
ingraph::__private::graphql::Crossed(Self::label(self))}"
),
"a manifest field is HELD and crossed out of: {wrapped}"
);
assert!(
!wrapped.contains("asyncfn__async_graphql_label(&self)->String{"),
"and never handed back bare, which is what put it on the library's own map: {wrapped}"
);
}
#[test]
fn the_walk_names_exactly_the_readers_the_rewrite_declares() {
let model = wrapped();
let walked: Vec<String> = model
.emitted_methods()
.iter()
.map(|emitted| emitted.name.to_string())
.collect();
assert_eq!(walked, own_methods(&emission(&model)));
assert_eq!(walked, ["width", "label"]);
}
fn dense_of(model: &FieldsModel) -> String {
prettyplease::unparse(&emission(model))
.split_whitespace()
.collect::<String>()
}
fn minted(file: &syn::File, name: &str) -> String {
let mut item = items(file)
.into_iter()
.find_map(|item| match item {
syn::Item::Struct(item) if item.ident == name => Some(item.clone()),
_ => None,
})
.unwrap_or_else(|| panic!("`{name}` is minted"));
item.attrs.retain(|attr| !attr.path().is_ident("doc"));
item.to_token_stream().to_string().replace(' ', "")
}
fn structs(file: &syn::File) -> Vec<String> {
items(file)
.into_iter()
.filter_map(|item| match item {
syn::Item::Struct(item) => Some(item.ident.to_string()),
_ => None,
})
.collect()
}
#[test]
fn a_single_activation_mints_one_predicate_and_seats_it_at_both_rows() {
let stored = FieldsModel {
entity: false,
..dimensions()
};
assert_eq!(
structs(&emission(&stored)),
["DimensionsColumnFilter", "DimensionsComparison"]
);
assert!(
dense_of(&stored).contains(
"CompositeFilterMarkerforDimensions{typeFilter=DimensionsColumnFilter;typeColumnFilter=DimensionsColumnFilter;}"
),
"the stored face takes both seats"
);
let projected = FieldsModel {
record: None,
..dimensions()
};
assert_eq!(
structs(&emission(&projected)),
["DimensionsFilter"],
"an entity-hosted fragment mints the full face and no storage answer at all"
);
assert!(
dense_of(&projected).contains(
"CompositeFilterMarkerforDimensions{typeFilter=DimensionsFilter;typeColumnFilter=DimensionsFilter;}"
),
"and the full face takes both seats"
);
}
#[test]
fn the_two_faces_differ_by_the_word_column_and_nothing_else() {
let file = emission(&dimensions());
let full = minted(&file, "DimensionsFilter");
let stored = minted(&file, "DimensionsColumnFilter").replace("ColumnFilter", "Filter");
assert_eq!(full, stored);
}
#[test]
fn the_stored_face_drops_a_skipped_field_and_the_full_face_keeps_it() {
use crate::model::Fill;
let mut model = dimensions();
model.fields[1].skip = Some(Fill {
at: proc_macro2::Span::call_site(),
named: None,
});
let file = emission(&model);
assert!(
minted(&file, "DimensionsFilter").contains("label:"),
"memory is the data, so a rowless host may ask about it"
);
assert!(
!minted(&file, "DimensionsColumnFilter").contains("label:"),
"and a row-holding host may not: what it would compare is a raise's fill"
);
}
#[test]
fn the_bind_and_the_read_are_behind_the_sqlx_gate() {
let emitted = dense_of(&dimensions());
for face in ["Carrier", "Assemble"] {
assert!(
emitted.contains(face),
"the {face} row is emitted: {emitted}"
);
}
let file = emission(&dimensions());
for row in bound(&file) {
assert!(
!row.contains("Carrier") && !row.contains("Assemble"),
"and neither is a bare impl the walk can see: {row}"
);
}
}
#[test]
fn the_bind_pushes_one_placeholder_per_column_with_its_own_separator() {
let emitted = dense_of(&dimensions());
assert_eq!(
emitted.matches("::push_bind(&self.").count(),
2,
"one bind per field: {emitted}"
);
assert_eq!(
emitted.matches("push(__ingraph_qb,\",\")").count(),
1,
"and one comma between the two: {emitted}"
);
}
#[test]
fn the_width_and_the_read_name_the_columns_from_one_list() {
let emitted = dense_of(&dimensions());
assert!(
emitted.contains(
"const__INGRAPH_FRAGMENT_FIELDS:&[&'static::ingraph::__private::field::FieldName]=&[\
::ingraph::__private::field::FieldName::new(\"width\"),\
::ingraph::__private::field::FieldName::new(\"label\"),]"
),
"the one list: {emitted}"
);
assert!(
emitted.contains("ColumnName::of(__INGRAPH_FRAGMENT_FIELDS[0usize],)"),
"the width indexes it: {emitted}"
);
assert!(
emitted.contains("__INGRAPH_FRAGMENT_FIELDS[0usize],__ingraph_under)?"),
"and so does the read: {emitted}"
);
assert!(
!emitted.contains("FieldName::new(\"width\"),__ingraph_under"),
"so no read spells a name of its own: {emitted}"
);
}
#[test]
fn the_raise_is_a_literal_for_a_held_fragment_and_a_call_for_a_wrapped_one() {
assert!(
dense_of(&dimensions()).contains("Ok(Self{width,label,})"),
"the struct literal"
);
let wrapped = dense_of(&wrapped());
assert!(
wrapped.contains(
"Ok(Self(upstream::Dimensions::new(__ingraph_cross(width),__ingraph_cross(label))))"
),
"the default law: every column a positional argument to `new`, crossed: {wrapped}"
);
}
#[test]
fn a_wordless_fragment_is_no_position_in_an_order() {
assert!(!dense_of(&dimensions()).contains("CursorValue"));
let keyed = FieldsModel {
cursor: Some(Vec::new()),
..dimensions()
};
let emitted = dense_of(&keyed);
assert!(emitted.contains("CursorValueforDimensions"), "{emitted}");
assert_eq!(
emitted.matches("write_member(&self.").count(),
2,
"one framed member per key column: {emitted}"
);
assert_eq!(
emitted.matches("read_member(&mut__ingraph_rest,)?").count(),
2,
"and one read back: {emitted}"
);
assert!(
emitted.contains("is_empty(__ingraph_rest)"),
"with a trailing byte refused: {emitted}"
);
}
#[test]
fn a_pinned_key_emits_what_the_bare_word_emits() {
let bare = FieldsModel {
cursor: Some(Vec::new()),
..dimensions()
};
let pinned = FieldsModel {
cursor: Some(vec![ident("width"), ident("label")]),
..dimensions()
};
assert_eq!(dense_of(&bare), dense_of(&pinned));
}
fn detection() -> FieldsModel {
FieldsModel {
fragment: ident("ObjectDetection"),
fields: vec![
column("bounds", "BoundingBox", Projection::Borrowed),
flattened("classification", "Classification"),
],
..dimensions()
}
}
#[test]
fn an_inner_mount_lends_its_name_unless_it_was_flattened() {
let emitted = dense_of(&detection());
assert!(
emitted.contains("column::shape::<BoundingBox,>(::ingraph::__private::column::ColumnName::of("),
"the nested seat lends its name: {emitted}"
);
assert!(
emitted.contains("column::flattened::<Classification>()"),
"and the flattened one lends none: {emitted}"
);
}
#[test]
fn a_flattened_mount_reads_at_the_fragments_own_path() {
let emitted = dense_of(&detection());
assert!(
emitted.contains("assembled(__ingraph_row,__INGRAPH_FRAGMENT_FIELDS[0usize],__ingraph_under)?"),
"the nested seat descends a segment: {emitted}"
);
assert!(
emitted.contains("assembled_flattened(__ingraph_row,__ingraph_under)?"),
"and the flattened one does not: {emitted}"
);
assert!(
!emitted.contains("__INGRAPH_FRAGMENT_FIELDS[1usize]"),
"so nothing indexes the name it did not lend: {emitted}"
);
}
#[test]
fn a_flattened_mount_renders_at_the_address_it_was_handed() {
let emitted = dense_of(&detection());
assert!(
emitted
.contains("At::frame(__ingraph_at,::ingraph::__private::field::FieldName::new(\"bounds\"),)"),
"the nested seat pushes its frame: {emitted}"
);
assert_eq!(
emitted.matches("At::frame(").count(),
1,
"and the flattened one pushes none: {emitted}"
);
assert!(
emitted.contains("apply(&self.classification,__ingraph_at,__ingraph_builder)?"),
"so it renders where the whole fragment was applied: {emitted}"
);
}
#[test]
fn the_rendered_names_are_fenced_only_where_a_field_was_flattened() {
let plain = dense_of(&dimensions());
assert!(
!plain.contains("distinct("),
"a fragment that flattens nothing cannot collide: {plain}"
);
let emitted = dense_of(&detection());
assert_eq!(
emitted.matches("distinct(<ObjectDetectionas").count(),
2,
"one assertion per field, over the impl's own const: {emitted}"
);
assert!(
emitted.contains("wouldrender`classification`intoacolumn"),
"and the one that fires names the field: {emitted}"
);
}
#[test]
fn every_key_member_is_asserted_to_span_one_column() {
let keyed = FieldsModel {
cursor: Some(Vec::new()),
..detection()
};
let emitted = dense_of(&keyed);
assert_eq!(
emitted.matches("::SEGMENTS.is_empty(),\"`").count(),
2,
"one width assertion per key member: {emitted}"
);
assert!(
emitted
.contains("<BoundingBoxas::ingraph::__private::column::ColumnKind>::SEGMENTS.is_empty()"),
"each over the member's own type: {emitted}"
);
assert!(
!dense_of(&detection()).contains("SEGMENTS.is_empty()"),
"and a fragment with no key asserts nothing about a width"
);
}
#[test]
fn the_comparison_pair_is_emitted_per_declared_dialect_and_nowhere_else() {
use crate::model::DatabaseKind;
let named = FieldsModel {
record: Some(super::RecordHost {
databases: vec![built(DatabaseKind::Sqlite), built(DatabaseKind::Postgres)],
write: None,
read: None,
}),
..dimensions()
};
let emitted = dense_of(&named);
assert_eq!(
emitted
.matches("TryFromFilter<DimensionsColumnFilter>")
.count(),
2,
"one crossing per declared dialect: {emitted}"
);
assert_eq!(
emitted
.matches("::core::default::Defaultfor DimensionsComparison<")
.count(),
0,
"the empty predicate is written at a concrete backend rather than generically"
);
for (gate, backend) in [
("if_sqlite!", "sqlx::Sqlite"),
("if_postgres!", "sqlx::Postgres"),
] {
let dense = gate.replace(' ', "");
assert!(
emitted.contains(&dense),
"each pair rides its own backend's gate: {emitted}"
);
assert!(
emitted.contains(&backend.replace(' ', "")),
"and names that backend concretely: {emitted}"
);
}
}
#[test]
fn the_bare_word_emits_the_pair_at_a_parameter() {
let emitted = dense_of(&dimensions());
for row in [
"::ingraph::__private::comparison::TryFromFilter<DimensionsColumnFilter>\
forDimensionsComparison<__INGRAPH_DB__>where",
"impl<__INGRAPH_DB__>::core::default::DefaultforDimensionsComparison<__INGRAPH_DB__>where",
] {
assert!(
emitted.contains(row),
"one pair over the parameter: {emitted}"
);
}
for member in ["u32", "String"] {
assert!(
emitted.contains(&format!(
"as::ingraph::__private::comparison::ToCrossedComparison<{member},__INGRAPH_DB__,>>::cross"
)),
"each member crosses through its own kind's row: {emitted}"
);
assert!(
emitted.contains(&format!(
"as::ingraph::__private::comparison::ToCrossedComparison<{member},__INGRAPH_DB__,>>::empty"
)),
"and answers the empty predicate through the same one: {emitted}"
);
}
for absent in [
"if_sqlite!",
"if_postgres!",
"sqlx::Sqlite",
"sqlx::Postgres",
] {
assert!(
!emitted.contains(&absent.replace(' ', "")),
"the generic arm names no dialect: {absent} in {emitted}"
);
}
assert!(
!emitted.contains("as::ingraph::__private::comparison::TryFromFilter<<<u32"),
"the body reaches no comparison through its projection: {emitted}"
);
}
#[test]
fn the_generic_clause_states_one_row_per_kind_and_not_per_field() {
let mut model = dimensions();
model
.fields
.push(column("height", "u32", Projection::Copied));
let emitted = dense_of(&model);
let row =
"::ColumnFilter:::ingraph::__private::comparison::ToCrossedComparison<u32,__INGRAPH_DB__,>,";
assert_eq!(
emitted.matches(row).count(),
2,
"TWO clauses carry the row — the crossing's and the empty predicate's — and neither repeats it \
for the second `u32` field: {emitted}"
);
for member in ["width", "height", "label"] {
assert!(
emitted.contains(&format!("__ingraph_filter.{member}")),
"every member is still crossed: {emitted}"
);
}
}
#[test]
fn a_named_dialect_never_reaches_the_generic_arm() {
use crate::model::DatabaseKind;
let named = FieldsModel {
record: Some(super::RecordHost {
databases: vec![built(DatabaseKind::Sqlite)],
write: None,
read: None,
}),
..dimensions()
};
let emitted = dense_of(&named);
assert!(
!emitted.contains("ToCrossedComparison"),
"a named dialect discharges its members' rows rather than carrying them: {emitted}"
);
assert!(
!emitted.contains("impl<__INGRAPH_DB__>::ingraph::__private::comparison::TryFromFilter<"),
"and writes its crossing at the backend rather than at the parameter: {emitted}"
);
assert_eq!(
emitted
.matches("impl<__INGRAPH_DB__>::core::default::Default")
.count(),
0,
"including the empty predicate: {emitted}"
);
}
#[test]
fn a_conditional_member_leaves_the_crossing_and_the_constructor() {
use crate::model::{Condition, DatabaseKind};
let mut model = dimensions();
model.fields[1].condition = Condition::of(vec![syn::parse_quote!(#[cfg(any())])], Vec::new());
for (arm, emitted) in [
("the parameter", dense_of(&model)),
(
"the backend",
dense_of(&FieldsModel {
record: Some(super::RecordHost {
databases: vec![built(DatabaseKind::Sqlite)],
write: None,
read: None,
}),
..model.clone()
}),
),
] {
assert!(
emitted.contains("#[cfg(any())]letlabel=match__ingraph_filter.label"),
"{arm}: the conditional member's leg rides its own gate: {emitted}"
);
assert!(
emitted.contains("Self::new(width,#[cfg(any())]label"),
"{arm}: and so does the argument that hands it over: {emitted}"
);
}
let plain = dense_of(&dimensions());
assert!(
plain.contains("Self::new(width,label)"),
"no gate, no change: {plain}"
);
}
#[test]
fn the_swap_reaches_the_generic_arm_the_same_way() {
let mounted = FieldsModel {
filter: Some(syn::parse_quote!(faces::DimensionsWhere)),
..dimensions()
};
let emitted = dense_of(&mounted);
assert!(
!emitted.contains("TryFromFilter<DimensionsColumnFilter>"),
"the author's predicate brings its own crossing: {emitted}"
);
assert!(
emitted.contains("impl<__INGRAPH_DB__>::core::default::DefaultforDimensionsComparison"),
"and the empty predicate stays, being a fact about the comparison: {emitted}"
);
}
#[test]
fn the_pair_walks_the_participation_and_not_the_declaration() {
use crate::model::{DatabaseKind, Fill};
let mut model = FieldsModel {
record: Some(super::RecordHost {
databases: vec![built(DatabaseKind::Sqlite)],
write: None,
read: None,
}),
..dimensions()
};
model.fields[1].skip = Some(Fill {
at: proc_macro2::Span::call_site(),
named: None,
});
let emitted = dense_of(&model);
assert!(
emitted.contains("__ingraph_filter.width"),
"the column that stays is crossed: {emitted}"
);
assert!(
!emitted.contains("__ingraph_filter.label"),
"and the one with no column anywhere is not: {emitted}"
);
}
#[test]
fn a_mounted_filter_replaces_the_generated_one_and_what_it_lowered_into() {
use crate::model::DatabaseKind;
let mounted = FieldsModel {
filter: Some(syn::parse_quote!(faces::DimensionsWhere)),
record: Some(super::RecordHost {
databases: vec![built(DatabaseKind::Sqlite)],
write: None,
read: None,
}),
..dimensions()
};
let emitted = dense_of(&mounted);
for generated in ["structDimensionsFilter", "structDimensionsColumnFilter"] {
assert!(
!emitted.contains(generated),
"NEITHER generated predicate is declared — one word, one predicate: {emitted}"
);
}
assert!(
!emitted.contains("ToDatabaseComparison<Dimensions,DB>forDimensionsColumnFilter"),
"nor the map row that said what it compares: {emitted}"
);
assert!(
!emitted.contains("TryFromFilter<DimensionsColumnFilter>"),
"nor the value-level crossing beside it: {emitted}"
);
assert!(
!emitted.contains("InputObjectType"),
"and the input face a generated predicate registers is gone with the struct: {emitted}"
);
assert!(
emitted.contains(
"CompositeFilterMarkerforDimensions{typeFilter=faces::DimensionsWhere;typeColumnFilter=faces::DimensionsWhere;}"
),
"the marker row names the author's type at BOTH seats, which is the swap being a swap: \
{emitted}"
);
assert!(
emitted.contains("DefaultMarkerforDimensions"),
"and the reading is unmoved, which is why no holder learns a word: {emitted}"
);
assert!(
emitted.contains("::core::default::DefaultforDimensionsComparison<"),
"the EMPTY predicate is a fact about the comparison and stays: {emitted}"
);
}
#[test]
fn a_mounted_filter_owes_what_a_holder_holds_at_its_own_span() {
let mounted = FieldsModel {
filter: Some(syn::parse_quote!(faces::DimensionsWhere)),
..dimensions()
};
let emitted = dense_of(&mounted);
assert!(emitted.contains("trait__IngraphMountedFilter"), "{emitted}");
assert!(
emitted.contains("trait__IngraphMountedInput"),
"the wire obligation rides the wire activation: {emitted}"
);
let quiet = FieldsModel {
wire: None,
..mounted
};
let emitted = dense_of(&quiet);
assert!(
emitted.contains("trait__IngraphMountedFilter"),
"a holder HOLDS the predicate whatever this declaration publishes: {emitted}"
);
assert!(
!emitted.contains("trait__IngraphMountedInput"),
"but a declaration with no face asks its predicate for none either: {emitted}"
);
}
fn delegating() -> FieldsModel {
FieldsModel {
delegates: vec![
crate::delegate::Delegate {
signature: syn::parse_quote!(fn label(&self) -> String),
exclusive: false,
wire: vec![crate::delegate::DelegateSkin {
kind: crate::model::GraphqlKind::AsyncGraphql,
rename: None,
}],
on_self: None,
},
crate::delegate::Delegate {
signature: syn::parse_quote!(fn pixels(&self) -> u64),
exclusive: false,
wire: vec![crate::delegate::DelegateSkin {
kind: crate::model::GraphqlKind::AsyncGraphql,
rename: Some(syn::parse_quote!("pixelCount")),
}],
on_self: None,
},
crate::delegate::Delegate {
signature: syn::parse_quote!(fn halve(&mut self)),
exclusive: true,
wire: Vec::new(),
on_self: None,
},
],
..wrapped()
}
}
#[test]
fn a_delegate_forwards_onto_the_value_the_wrapper_holds() {
let emitted = delegating().emit().to_string();
assert!(
emitted.contains("fn label (& self) -> String { (& self . 0) . label () }"),
"{emitted}"
);
assert!(
emitted.contains("fn halve (& mut self) { (& mut self . 0) . halve () }"),
"an exclusive receiver mutates in place, at no conversion: {emitted}"
);
}
#[test]
fn a_lifted_delegate_rides_the_holding_adapter() {
let emitted = delegating().emit().to_string();
assert!(
emitted.contains(r#"# [graphql (name = "label")]"#),
"{emitted}"
);
assert!(
emitted.contains(r#"# [graphql (name = "pixelCount")]"#),
"and `rename` moves the word a client writes: {emitted}"
);
assert!(
emitted.contains(
"Crossed < u64 > { :: ingraph :: __private :: graphql :: Crossed (Self :: pixels (self)) }"
),
"the manufactured value moves into the adapter, reached fully qualified: {emitted}"
);
assert!(
!emitted.contains(r#"# [graphql (name = "halve")]"#),
"an exclusive receiver is never lifted: {emitted}"
);
}
#[test]
fn a_fragment_with_no_seat_pays_nothing_for_it() {
let emitted = dimensions().emit().to_string();
assert!(!emitted.contains("Crossed <"), "{emitted}");
}
#[test]
fn an_own_fragments_delegate_is_lifted_and_never_forwarded() {
let own = FieldsModel {
delegates: vec![crate::delegate::Delegate {
signature: syn::parse_quote!(fn label(&self) -> String),
exclusive: false,
wire: vec![crate::delegate::DelegateSkin {
kind: crate::model::GraphqlKind::AsyncGraphql,
rename: None,
}],
on_self: None,
}],
..dimensions()
};
let emitted = own.emit().to_string();
assert!(
emitted.contains(r#"# [graphql (name = "label")]"#),
"the entry is a field of the object: {emitted}"
);
assert!(
emitted.contains(
"Crossed < String > { :: ingraph :: __private :: graphql :: Crossed (Self :: label (self)) }"
),
"reached through `Self`, which is where resolution answers: {emitted}"
);
assert!(
!emitted.contains("fn label (& self) -> String { (& self . 0)"),
"and NO forwarding method is minted — the method is already the author's: {emitted}"
);
let wrapper = FieldsModel {
remote: Some(syn::parse_quote!(upstream::Dimensions)),
..own
};
assert!(
wrapper
.emit()
.to_string()
.contains("fn label (& self) -> String { (& self . 0) . label () }"),
"where a wrapper needs one, it is minted — the same entry, the other mode"
);
}
#[test]
fn a_waived_entry_mints_no_forwarding_half() {
let waived = FieldsModel {
delegates: vec![crate::delegate::Delegate {
signature: syn::parse_quote!(fn label(&self) -> String),
exclusive: false,
wire: vec![crate::delegate::DelegateSkin {
kind: crate::model::GraphqlKind::AsyncGraphql,
rename: None,
}],
on_self: Some(ident("self")),
}],
..wrapped()
};
let emitted = waived.emit().to_string();
assert!(
!emitted.contains("(& self . 0) . label ()"),
"the forwarding half is not emitted: {emitted}"
);
assert!(
emitted.contains(
"Crossed < String > { :: ingraph :: __private :: graphql :: Crossed (Self :: label (self)) }"
),
"and the LIFTED half is untouched, reaching the author's method through `Self`: {emitted}"
);
}
#[test]
fn a_waiver_moves_one_entry_and_no_other() {
let before = delegating().emit().to_string();
let mut model = delegating();
model.delegates[0].on_self = Some(ident("self"));
let after = model.emit().to_string();
assert!(
before.contains("fn label (& self) -> String { (& self . 0) . label () }"),
"{before}"
);
assert!(!after.contains("(& self . 0) . label ()"), "{after}");
assert!(
after.contains("fn halve (& mut self) { (& mut self . 0) . halve () }"),
"the entry beside it is minted unchanged: {after}"
);
assert!(
after.contains("Crossed (Self :: pixels (self))"),
"and so is every lifted half: {after}"
);
}
fn spanned() -> FieldsModel {
FieldsModel {
fragment: ident("Span"),
fields: vec![
deriving("pts", "i64", "nanos", "Span::nanos", "i64"),
column("label", "String", Projection::Borrowed),
],
..dimensions()
}
}
#[test]
fn a_derived_column_follows_its_source_in_the_layout() {
let dense = dense_of(&spanned());
assert!(
dense.contains(r#"FieldName::new("pts"),::ingraph::__private::field::FieldName::new("nanos"),::ingraph::__private::field::FieldName::new("label"),]"#),
"the names const carries the derived column between its source and the field after it: {dense}"
);
assert!(
dense.contains(
"column::derived::<Span,i64,>(Span::nanos,::ingraph::__private::column::ColumnName::of(__INGRAPH_FRAGMENT_FIELDS[1usize],),)"
),
"and the width names it through `derived`, which is `shape` with the function as a parameter it \
never calls: {dense}"
);
}
#[test]
fn the_bind_carries_a_derived_column_and_the_raise_does_not() {
let dense = dense_of(&spanned());
assert!(
dense.contains("push_bind(&Span::nanos(self),__ingraph_qb);"),
"the bind pushes what the function returns, at the position the layout gave it: {dense}"
);
assert!(
dense.contains("letlabel:String=::ingraph::__private::column::assembled(__ingraph_row,__INGRAPH_FRAGMENT_FIELDS[2usize],__ingraph_under)?;"),
"the read indexes the LAYOUT's positions, so the field after a derived column still fetches its \
own name: {dense}"
);
assert!(
!dense.contains("Span::nanos(__ingraph_row"),
"and nothing reads the derived column back — the value is rebuilt from its sources: {dense}"
);
assert!(
dense.contains(
"i64:::ingraph::__private::column::Assemble<'__ingraph,__INGRAPH_ROW__>,String:::ingraph::__private::column::Assemble<'__ingraph,__INGRAPH_ROW__>,"
),
"the READ's clause owes a row for the declared types alone: {dense}"
);
}
#[test]
fn only_the_stored_face_has_a_slot_for_a_derived_column() {
let file = emission(&spanned());
assert!(
minted(&file, "SpanColumnFilter").contains("nanos"),
"a row-holding host may ask about it, which is what the word is for"
);
assert!(
!minted(&file, "SpanFilter").contains("nanos"),
"a rowless host holds the value, and there is no derived column in a value"
);
}
#[test]
fn a_derived_column_carries_the_condition_of_the_field_it_follows() {
let gate: syn::Attribute = syn::parse_quote!(#[cfg(feature = "nanos")]);
let mut model = spanned();
model.fields[0].condition = crate::model::Condition::of(vec![gate], Vec::new());
let dense = dense_of(&model);
assert!(
dense.contains(r#"FieldName::new("pts"),#[cfg(feature="nanos")]::ingraph::__private::field::FieldName::new("nanos"),"#),
"the gate reaches the source's name entry and the derived one alike: {dense}"
);
assert!(
dense.contains(
r#"#[cfg(feature="nanos")]::ingraph::__private::column::derived::<Span,i64,>(Span::nanos,"#
),
"and the segment it mints: {dense}"
);
assert!(
dense.contains("#[cfg(feature=\"nanos\")]{if__INGRAPH_AT_1>0{"),
"the bind asks the PLACE rather than the declaration ordinal, and the derived column has a \
place of its own: {dense}"
);
assert!(
dense.contains("__INGRAPH_AT_2:::core::primitive::usize=__INGRAPH_AT_1+"),
"so the field after a gated pair is two positions along when the predicate holds and none when \
it does not: {dense}"
);
}
fn canonical() -> FieldsModel {
FieldsModel {
fragment: ident("Track"),
fields: vec![
writing("frame_rate", "Rate", "Rate::reduced"),
column("codec", "String", Projection::Borrowed),
],
..dimensions()
}
}
fn canonical_at_sqlite() -> FieldsModel {
use crate::model::DatabaseKind;
FieldsModel {
record: Some(super::RecordHost {
databases: vec![built(DatabaseKind::Sqlite)],
write: None,
read: None,
}),
..canonical()
}
}
#[test]
fn the_write_reaches_the_bind_and_the_generic_crossing() {
let dense = dense_of(&canonical());
assert!(
dense.contains("push_bind(&__INGRAPH_FRAGMENT_WRITE_0(&self.frame_rate),__ingraph_qb);"),
"the BIND writes what the function returns, which is what makes the column canonical: {dense}"
);
assert!(
dense.contains("graphql::TryMapFilter<Rate,Rate,>>::try_map_filter(__ingraph_held,"),
"and the QUERY OPERAND is mapped through the seam a declared converter already crosses: {dense}"
);
assert!(
dense.contains("::Ok(__INGRAPH_FRAGMENT_WRITE_0(&__ingraph_operand)),)"),
"through the same path the bind spends, which is the whole of the two-site agreement: {dense}"
);
assert!(
dense.contains("push_bind(&self.codec,__ingraph_qb);")
&& !dense.contains("TryMapFilter<String"),
"the field that wrote no word binds what it holds and crosses at the identity: {dense}"
);
assert_eq!(
dense.matches("__INGRAPH_FRAGMENT_WRITE_0").count(),
3,
"THREE spellings and no more: the pin's own definition, and the two sites that read it. A \
fourth would be a face nobody ruled on, and a second would be a site left unspent: {dense}"
);
}
#[test]
fn the_write_reaches_the_concrete_crossing_too() {
let dense = dense_of(&canonical_at_sqlite());
assert!(
dense.contains("push_bind(&__INGRAPH_FRAGMENT_WRITE_0(&self.frame_rate),__ingraph_qb);"),
"the bind is the layout's, so it does not move when a dialect is named: {dense}"
);
assert!(
dense.contains("TryMapFilter<Rate,Rate>>::try_map_filter(__ingraph_held,"),
"and the concrete pair maps the operand through the same path: {dense}"
);
assert!(
dense.contains("::Ok(__INGRAPH_FRAGMENT_WRITE_0(&__ingraph_operand)),)"),
"naming the declaration's own function and no other: {dense}"
);
assert_eq!(
dense.matches("__INGRAPH_FRAGMENT_WRITE_0").count(),
3,
"the same three at the other arm — one definition, two readers, whichever pair the dialect \
word selected: {dense}"
);
}
#[test]
fn a_transform_is_pinned_where_no_feature_reaches_it() {
let dense = dense_of(&canonical());
assert!(
dense.contains("const__INGRAPH_FRAGMENT_WRITE_0:fn(&Rate)->Rate=Rate::reduced;"),
"the pin is the const's own TYPE, which is `E0308` on a wrong signature and `E0433` on a path \
naming nothing — at the string the author wrote: {dense}"
);
let gated = {
let gate: syn::Attribute = syn::parse_quote!(#[cfg(feature = "rates")]);
let mut model = canonical();
model.fields[0].condition = crate::model::Condition::of(vec![gate], Vec::new());
dense_of(&model)
};
assert!(
gated.contains(
"#[cfg(feature=\"rates\")]const__INGRAPH_FRAGMENT_WRITE_0:fn(&Rate)->Rate=Rate::reduced;"
),
"and it rides the field's own predicate, because a build that removed the field removed the \
transform with it: {gated}"
);
}
#[test]
fn the_read_wraps_the_fetch_alone() {
let mut model = canonical();
model.fields[0].read = Some(syn::parse_str("Rate::spelled").expect("a path"));
let dense = dense_of(&model);
assert!(
dense.contains(
"letframe_rate:Rate=__INGRAPH_FRAGMENT_READ_0(&::ingraph::__private::column::assembled(\
__ingraph_row,__INGRAPH_FRAGMENT_FIELDS[0usize],__ingraph_under)?);"
),
"the fetch is what the mirror is applied to, and the annotation still fixes the row: {dense}"
);
assert!(
!dense.contains("__INGRAPH_FRAGMENT_READ_0(&__ingraph_operand)"),
"and no operand crosses through it — a query travels the WRITE's direction: {dense}"
);
assert!(
dense.contains("const__INGRAPH_FRAGMENT_READ_0:fn(&Rate)->Rate=Rate::spelled;"),
"the mirror is pinned to the same shape as its twin: {dense}"
);
}
#[test]
fn a_derived_column_stands_outside_its_sources_transform() {
let mut model = canonical();
model.fields[0].derived = vec![super::Derived {
column: crate::name::RustSafeName::new("rate_hz", proc_macro2::Span::call_site()),
from: syn::parse_str("Track::rate_hz").expect("a path"),
ty: syn::parse_str("f64").expect("a type"),
}];
let dense = dense_of(&model);
assert!(
dense.contains("push_bind(&__INGRAPH_FRAGMENT_WRITE_0(&self.frame_rate),__ingraph_qb);"),
"the source field still writes through its own transform: {dense}"
);
assert!(
dense.contains("push_bind(&Track::rate_hz(self),__ingraph_qb);"),
"and the derived column binds what its own function returns, off the value as declared: {dense}"
);
assert!(
!dense.contains("__INGRAPH_FRAGMENT_WRITE_0(&Track::rate_hz")
&& !dense.contains("Track::rate_hz(&__INGRAPH_FRAGMENT_WRITE_0"),
"neither wrapping the other, which the types already refuse wherever they differ: {dense}"
);
assert!(
!dense.contains("TryMapFilter<f64,f64>"),
"and the derived column's own slot crosses at the identity, having no word of its own: {dense}"
);
}
#[test]
fn a_fragment_with_no_transform_expands_token_for_token() {
let plain = FieldsModel {
fields: vec![
column("frame_rate", "Rate", Projection::Borrowed),
column("codec", "String", Projection::Borrowed),
],
..canonical()
};
let mut cleared = canonical();
cleared.fields[0].write = None;
assert_eq!(
dense_of(&cleared),
dense_of(&plain),
"the seat costs nothing where nothing was written"
);
}
fn reduced() -> FieldsModel {
FieldsModel {
fragment: ident("Ratio"),
fields: vec![
column("num", "u32", Projection::Copied),
column("den", "u32", Projection::Copied),
],
record: Some(super::RecordHost {
databases: Vec::new(),
write: Some(syn::parse_str("Ratio::reduced").expect("a path")),
read: None,
}),
..dimensions()
}
}
#[test]
fn the_head_write_reaches_the_bind_and_the_cursor() {
let keyed = FieldsModel {
cursor: Some(Vec::new()),
..reduced()
};
let dense = dense_of(&keyed);
assert!(
dense.contains("const__INGRAPH_FRAGMENT_HEAD_WRITE:fn(&Ratio)->Ratio=Ratio::reduced;"),
"the pin is `fn(&Self) -> Self`, which is `E0308` on a wrong signature and `E0433` on a path \
naming nothing — at the string the author wrote: {dense}"
);
assert_eq!(
dense
.matches(
"let__ingraph_whole:Self=__INGRAPH_FRAGMENT_HEAD_WRITE(self);\
#[allow(unused_variables)]let__ingraph_whole:&Self=&__ingraph_whole;"
)
.count(),
2,
"ONE call per site and not one per column: a reduction computes a gcd, and nothing promises a \
household's own method is cheap: {dense}"
);
assert!(
dense.contains("push_bind(&__ingraph_whole.num,__ingraph_qb);")
&& dense.contains("push_bind(&__ingraph_whole.den,__ingraph_qb);"),
"the BIND reads every column off the transformed whole: {dense}"
);
assert!(
dense.contains("write_member(&__ingraph_whole.num,__ingraph_out,)")
&& dense.contains("write_member(&__ingraph_whole.den,__ingraph_out,)"),
"and so does the CURSOR's write, which is the site a one-site seat would have left lying: \
{dense}"
);
assert_eq!(
dense.matches("__INGRAPH_FRAGMENT_HEAD_WRITE").count(),
3,
"THREE spellings and no more: the pin's own definition, and the two sites that read it. A \
fourth would be a face nobody ruled on, and a second would be a site left unspent: {dense}"
);
}
#[test]
fn the_head_write_reaches_whatever_sites_the_declaration_has() {
let dense = dense_of(&reduced());
assert!(
!dense.contains("CursorValue"),
"no `cursor` word, no keyset row: {dense}"
);
assert_eq!(
dense.matches("__INGRAPH_FRAGMENT_HEAD_WRITE").count(),
2,
"the definition and the bind, which is the whole list here: {dense}"
);
}
#[test]
fn the_head_write_leaves_the_crossing_where_it_stands() {
let at_sqlite = FieldsModel {
record: Some(super::RecordHost {
databases: vec![built(crate::model::DatabaseKind::Sqlite)],
write: Some(syn::parse_str("Ratio::reduced").expect("a path")),
read: None,
}),
..reduced()
};
for dense in [dense_of(&reduced()), dense_of(&at_sqlite)] {
assert!(
dense.contains("TryFromFilter<RatioColumnFilter>"),
"the crossing is still emitted: {dense}"
);
assert!(
!dense.contains("__INGRAPH_FRAGMENT_HEAD_WRITE(&__ingraph_operand)")
&& !dense.contains("TryMapFilter<Ratio,Ratio"),
"and nothing in it spends the head word — there is no operand of the fragment's own type for \
a whole-value function to touch, at either arm: {dense}"
);
}
}
#[test]
fn the_head_read_runs_last_on_the_value_the_columns_rebuilt() {
let mut model = FieldsModel {
cursor: Some(Vec::new()),
..reduced()
};
let host = model.record.as_mut().expect("the activation");
host.read = Some(syn::parse_str("Ratio::spread").expect("a path"));
let dense = dense_of(&model);
assert!(
dense.contains("const__INGRAPH_FRAGMENT_HEAD_READ:fn(&Ratio)->Ratio=Ratio::spread;"),
"the mirror is pinned to the same shape as its twin: {dense}"
);
assert_eq!(
dense
.matches("__INGRAPH_FRAGMENT_HEAD_READ(&Self{num,den")
.count(),
2,
"and it wraps the BUILT value at both read sites — the row's raise and the cursor's: {dense}"
);
assert!(
!dense.contains("__INGRAPH_FRAGMENT_HEAD_READ(&__ingraph_operand)"),
"no operand crosses through it — a query travels the WRITE's direction: {dense}"
);
assert_eq!(
dense.matches("__INGRAPH_FRAGMENT_HEAD_READ").count(),
3,
"one definition, two readers, exactly as the write half counts: {dense}"
);
}
#[test]
fn the_head_read_wraps_the_construction_protocol_too() {
let mut model = FieldsModel {
remote: Some(syn::parse_quote!(upstream::Ratio)),
..reduced()
};
model.record.as_mut().expect("the activation").read =
Some(syn::parse_str("Ratio::spread").expect("a path"));
let dense = dense_of(&model);
assert!(
dense.contains("__INGRAPH_FRAGMENT_HEAD_READ(&Self(upstream::Ratio::new("),
"the mirror is applied to the value the protocol built, not to the columns it was built from: \
{dense}"
);
}
#[test]
fn a_derived_column_reads_the_value_as_declared_under_a_head_write() {
let mut model = reduced();
model.fields[0].derived = vec![super::Derived {
column: crate::name::RustSafeName::new("spelled", proc_macro2::Span::call_site()),
from: syn::parse_str("Ratio::spelled").expect("a path"),
ty: syn::parse_str("String").expect("a type"),
}];
let dense = dense_of(&model);
assert!(
dense.contains("push_bind(&__ingraph_whole.num,__ingraph_qb);"),
"the declared column still binds off the transformed whole: {dense}"
);
assert!(
dense.contains("push_bind(&Ratio::spelled(self),__ingraph_qb);"),
"and the derived column's function reads `self` — the value AS DECLARED: {dense}"
);
assert!(
!dense.contains("Ratio::spelled(__ingraph_whole)"),
"never the transformed one, which is the reading that could not be undone: {dense}"
);
}
#[test]
fn a_field_transform_composes_under_the_head_one() {
let mut model = reduced();
model.fields[1].write = Some(syn::parse_str("positive").expect("a path"));
let dense = dense_of(&model);
assert!(
dense.contains("push_bind(&__ingraph_whole.num,__ingraph_qb);"),
"the column with no word of its own binds the transformed whole's value: {dense}"
);
assert!(
dense.contains("push_bind(&__INGRAPH_FRAGMENT_WRITE_1(&__ingraph_whole.den),__ingraph_qb);"),
"and the column that wrote one crosses through it AFTER the head word, which is the only \
order `fn(&Self) -> Self` and `fn(&T) -> T` compose in: {dense}"
);
}
#[test]
fn a_fragment_with_no_head_transform_expands_token_for_token() {
let mut cleared = reduced();
cleared.record.as_mut().expect("the activation").write = None;
let plain = FieldsModel {
fragment: ident("Ratio"),
fields: vec![
column("num", "u32", Projection::Copied),
column("den", "u32", Projection::Copied),
],
..dimensions()
};
assert_eq!(
dense_of(&cleared),
dense_of(&plain),
"the seat costs nothing where nothing was written"
);
}
#[test]
fn a_mounted_lowering_replaces_the_product_at_that_dialect_alone() {
use crate::model::DatabaseKind;
let mounted = FieldsModel {
record: Some(super::RecordHost {
databases: vec![
super::BuiltFor {
kind: DatabaseKind::Sqlite,
comparison: Some(syn::parse_quote!(lowering::SqlDimensionsComparison)),
cursor: None,
},
built(DatabaseKind::Postgres),
],
write: None,
read: None,
}),
..dimensions()
};
let emitted = dense_of(&mounted);
assert!(
emitted.contains(
"ToDatabaseComparison<Dimensions,::ingraph::__private::sqlx::Sqlite>\
forDimensionsColumnFilter{typeComparison=lowering::SqlDimensionsComparison;}"
),
"the mounted type IS what the predicate lowers into at that dialect: {emitted}"
);
assert!(
emitted.contains(
"ToDatabaseComparison<Dimensions,::ingraph::__private::sqlx::Postgres>\
forDimensionsColumnFilter{typeComparison=DimensionsComparison<::ingraph::__private::sqlx::Postgres>;}"
),
"and a dialect with no mount keeps the framework's per-field product: {emitted}"
);
assert!(
!emitted.contains("ToDatabaseComparison<Dimensions,__INGRAPH_DB__"),
"the parameter arm cannot stand beside either — it overlaps both: {emitted}"
);
assert!(
emitted.contains("__IngraphMountedComparison0"),
"and the mount is audited at the dialect it was named at: {emitted}"
);
assert!(
!emitted.contains("__IngraphMountedComparison1"),
"one witness per MOUNT, not per dialect: {emitted}"
);
assert!(
emitted.contains(
"TryFromFilter<DimensionsColumnFilter>forDimensionsComparison<::ingraph::__private::sqlx::Sqlite>"
),
"the product it replaces is still emitted and still nameable: {emitted}"
);
}
#[test]
fn a_mounted_filter_and_a_mounted_lowering_meet_in_the_row_between_them() {
use crate::model::DatabaseKind;
let both = FieldsModel {
filter: Some(syn::parse_quote!(faces::DimensionsWhere)),
record: Some(super::RecordHost {
databases: vec![
super::BuiltFor {
kind: DatabaseKind::Sqlite,
comparison: Some(syn::parse_quote!(lowering::SqlDimensionsComparison)),
cursor: None,
},
built(DatabaseKind::Postgres),
],
write: None,
read: None,
}),
..dimensions()
};
let emitted = dense_of(&both);
assert!(
emitted.contains(
"ToDatabaseComparison<Dimensions,::ingraph::__private::sqlx::Sqlite>\
forfaces::DimensionsWhere{typeComparison=lowering::SqlDimensionsComparison;}"
),
"the author's filter lowers into the author's comparison, joined here: {emitted}"
);
assert!(
!emitted.contains("ToDatabaseComparison<Dimensions,::ingraph::__private::sqlx::Postgres>"),
"and the unmounted dialect writes no row at all — a generated comparison is a crossing only \
the author's predicate can state: {emitted}"
);
assert!(
emitted.contains("TryFromFilter<faces::DimensionsWhere>"),
"the audit asks the mount for a crossing from the AUTHOR's predicate: {emitted}"
);
}
#[test]
fn a_fragment_with_no_mounted_lowering_expands_token_for_token() {
use crate::model::DatabaseKind;
let named = FieldsModel {
record: Some(super::RecordHost {
databases: vec![built(DatabaseKind::Sqlite)],
write: None,
read: None,
}),
..dimensions()
};
let mut cleared = named.clone();
cleared
.record
.as_mut()
.expect("the activation")
.databases
.iter_mut()
.for_each(|one| one.comparison = None);
assert_eq!(
dense_of(&cleared),
dense_of(&named),
"the seat costs nothing where nothing was mounted"
);
}
fn coded() -> FieldsModel {
use crate::model::DatabaseKind;
FieldsModel {
cursor: Some(Vec::new()),
record: Some(super::RecordHost {
databases: vec![
super::BuiltFor {
kind: DatabaseKind::Sqlite,
comparison: None,
cursor: Some(syn::parse_quote!(codecs::RateCursor)),
},
built(DatabaseKind::Postgres),
],
write: Some(syn::parse_str("Ratio::reduced").expect("a path")),
read: Some(syn::parse_str("Ratio::spread").expect("a path")),
}),
..reduced()
}
}
#[test]
fn a_mounted_codec_forks_the_row_per_dialect() {
let dense = dense_of(&coded());
assert!(
dense.contains(
"impl::ingraph::__private::cursor::DialectCursor<::ingraph::__private::cursor::dialect::Sqlite,>forRatio{"
),
"SQLite gets a row of its own: {dense}"
);
assert!(
dense.contains(
"<codecs::RateCursoras::ingraph::__private::cursor::CursorCodec<Self,>>::encode(\
__ingraph_whole,__ingraph_out);"
),
"and it spends the codec, handed the value the head word returned: {dense}"
);
assert!(
dense.contains(
"let__ingraph_decoded:Self=<codecs::RateCursoras::ingraph::__private::cursor::\
CursorCodec<Self,>>::decode(__ingraph_bytes)?;"
) && dense.contains("Some(__INGRAPH_FRAGMENT_HEAD_READ(&__ingraph_decoded),)"),
"its read is the dual, with the domain mirror one call further on: {dense}"
);
assert!(
dense.contains(
"impl::ingraph::__private::cursor::DialectCursor<::ingraph::__private::cursor::dialect::Postgres,>forRatio"
) && dense.contains("write_member(&__ingraph_whole.num,__ingraph_out,);"),
"PostgreSQL was NAMED and mounted nothing, so it rides the framed walk — a mixed declaration is \
ordinary: {dense}"
);
assert!(
!dense.contains("::ingraph::__private::cursor::CursorValueforRatio"),
"and the dialect-free row is GONE: a value whose bytes are the engine's cannot also claim one \
form everywhere, which is `E0119` and is the fork being total: {dense}"
);
assert!(
dense.contains("SEGMENTS.is_empty()"),
"the WIDTH refusal stays: it is about the SQL keyset's column order, which a byte form has no \
bearing on: {dense}"
);
}
#[test]
fn only_the_framed_row_owes_the_members_their_own_codecs() {
let dense = dense_of(&coded());
let sqlite = dense
.split("DialectCursor<::ingraph::__private::cursor::dialect::Sqlite,>forRatio")
.nth(1)
.expect("the SQLite row");
assert!(
!sqlite.starts_with("where"),
"the mounted row calls no member's row, so it demands none: {sqlite}"
);
let postgres = dense
.split("DialectCursor<::ingraph::__private::cursor::dialect::Postgres,>forRatio")
.nth(1)
.expect("the PostgreSQL row");
assert!(
postgres.starts_with("whereu32:::ingraph::__private::cursor::CursorValue"),
"and the framed one states exactly what its walk spends: {postgres}"
);
}
#[test]
fn the_cursor_seam_names_a_marker_and_rides_no_gate() {
let dense = dense_of(&coded());
for dialect in ["Sqlite", "Postgres"] {
let head = format!("cursor::DialectCursor<::ingraph::__private::cursor::dialect::{dialect},>");
let at = dense
.find(&head)
.unwrap_or_else(|| panic!("the {dialect} row: {dense}"));
let before = &dense[..at];
assert!(
before.ends_with("#[automatically_derived]impl::ingraph::__private::"),
"the row stands on its own, with no gate wrapped round it: …{}",
&before[before.len().saturating_sub(120)..]
);
}
assert!(
!dense.contains("DialectCursor<::ingraph::__private::sqlx::"),
"and no driver is named in them — `cursor::dialect::…` is the key: {dense}"
);
}
#[test]
fn a_mounted_codec_is_audited_at_every_dialect_that_named_it() {
use crate::model::DatabaseKind;
let dense = dense_of(&coded());
assert!(
dense.contains("trait__IngraphMountedCursor0")
&& dense.contains("__ingraph_mounted::<codecs::RateCursor>")
&& dense.contains("mountsasits`sqlite`cursorcodec,anditdoesnotanswerthatseat"),
"one witness, spent at the author's path, in the seat's own words: {dense}"
);
assert!(
!dense.contains("__IngraphMountedCursor1"),
"and none for the dialect that mounted nothing: {dense}"
);
let differing = FieldsModel {
record: Some(super::RecordHost {
databases: vec![
super::BuiltFor {
kind: DatabaseKind::Sqlite,
comparison: None,
cursor: Some(syn::parse_quote!(codecs::RateSqlite)),
},
super::BuiltFor {
kind: DatabaseKind::Postgres,
comparison: None,
cursor: Some(syn::parse_quote!(codecs::RatePostgres)),
},
],
write: None,
read: None,
}),
..coded()
};
let dense = dense_of(&differing);
assert!(
dense.contains("__ingraph_mounted::<codecs::RateSqlite>")
&& dense.contains("__ingraph_mounted::<codecs::RatePostgres>"),
"DIFFERING codecs are the ordinary case, and each is audited on its own: {dense}"
);
assert!(
dense.contains("mountsasits`sqlite`cursorcodec")
&& dense.contains("mountsasits`postgres`cursorcodec"),
"each naming the dialect it was written at: {dense}"
);
}
#[test]
fn a_fragment_with_no_codec_keeps_the_framed_default() {
let framed = FieldsModel {
record: Some(super::RecordHost {
databases: vec![built(crate::model::DatabaseKind::Sqlite)],
write: Some(syn::parse_str("Ratio::reduced").expect("a path")),
read: Some(syn::parse_str("Ratio::spread").expect("a path")),
}),
..coded()
};
let dense = dense_of(&framed);
assert!(
dense.contains("impl::ingraph::__private::cursor::CursorValueforRatio")
&& dense.contains("write_member(&__ingraph_whole.num,__ingraph_out,)")
&& dense.contains("write_member(&__ingraph_whole.den,__ingraph_out,)"),
"ONE dialect-free row, framed — which the blanket answers at every dialect: {dense}"
);
assert!(
!dense.contains("DialectCursor") && !dense.contains("__IngraphMountedCursor"),
"and nothing of the seat is emitted beside it — no row, no call, no witness: {dense}"
);
assert!(
dense.contains("whereu32:::ingraph::__private::cursor::CursorValue"),
"the clause the framed walk owes is still stated: {dense}"
);
}