use crate::prefix::EmissionPrefix;
use quote::ToTokens;
use super::{
InterfaceDatabase, InterfaceField, InterfaceModel, MemberColumn, Operand, Pin, Tier,
default_derivations_name, default_fields_name, default_filter_name, default_id_name,
default_input_name, default_key_name, default_kind_name, default_order_by_name,
default_output_name, default_row_name,
};
use crate::{model::DatabaseKind, union::UnionMember};
pub(super) fn media() -> InterfaceModel {
InterfaceModel {
prefix: EmissionPrefix::default(),
vis: syn::parse_quote!(pub),
name: ident("Media"),
krate: syn::parse_quote!(::ingraph),
members: vec![
member("Video", syn::parse_quote!(Video)),
member("Audio", syn::parse_quote!(Audio)),
],
fields: vec![
InterfaceField {
name: ident("title"),
ty: syn::parse_quote!(String),
tier: Tier::Stored,
marker: None,
copy: false,
pins: Vec::new(),
wire: None,
operands: Vec::new(),
members: Vec::new(),
},
InterfaceField {
name: ident("mask"),
ty: syn::parse_quote!(Mask),
tier: Tier::Stored,
marker: None,
copy: true,
pins: vec![
Pin {
kind: DatabaseKind::Sqlite,
stored: Some(syn::parse_quote!(u32)),
},
Pin {
kind: DatabaseKind::Postgres,
stored: None,
},
],
wire: None,
operands: vec![Operand {
kind: DatabaseKind::Sqlite,
convert: syn::parse_quote!(narrow),
}],
members: vec![MemberColumn {
variant: ident("Audio"),
column: ident("flags"),
}],
},
InterfaceField {
name: ident("display_label"),
ty: syn::parse_quote!(String),
tier: Tier::Computed,
marker: None,
copy: false,
pins: Vec::new(),
wire: None,
operands: Vec::new(),
members: Vec::new(),
},
InterfaceField {
name: ident("checksum"),
ty: syn::parse_quote!(u64),
tier: Tier::TryComputed,
marker: None,
copy: true,
pins: Vec::new(),
wire: None,
operands: Vec::new(),
members: Vec::new(),
},
],
error: None,
computed_error: None,
persist: Vec::new(),
errors: Vec::new(),
operand_errors: Vec::new(),
plural: None,
connection: None,
edge: None,
}
}
pub(super) fn member(name: &str, ty: syn::Type) -> UnionMember {
UnionMember {
ident: ident(name),
ty,
}
}
pub(super) fn ident(name: &str) -> syn::Ident {
syn::Ident::new(name, proc_macro2::Span::call_site())
}
pub(super) fn emission(model: &InterfaceModel) -> syn::File {
syn::parse2(model.emit()).expect("the expansion parses")
}
pub(super) fn rendered(model: &InterfaceModel) -> String {
prettyplease::unparse(&emission(model))
}
pub(super) fn tight(tokens: impl ToTokens) -> String {
tokens.to_token_stream().to_string().replace(' ', "")
}
#[test]
fn the_member_face_is_the_unions_own_emission() {
let interface = media();
let union = crate::union::UnionModel {
krate: interface.krate.clone(),
vis: interface.vis.clone(),
name: interface.name.clone(),
members: interface.members.clone(),
error: interface.error.clone(),
graphql: Vec::new(),
};
assert_eq!(tight(interface.union_face()), tight(union.emit()));
}
#[test]
fn the_refusal_takes_the_declared_name_or_the_shared_convention() {
assert_eq!(media().error(), "MediaUnwrapError");
let mut renamed = media();
renamed.error = Some(ident("NoSuchMedia"));
assert_eq!(renamed.error(), "NoSuchMedia");
let rendered = rendered(&renamed);
assert!(rendered.contains("struct NoSuchMedia"), "{rendered}");
assert!(!rendered.contains("MediaUnwrapError"), "{rendered}");
}
#[test]
fn every_field_is_in_exactly_one_tier() {
let model = media();
let stored: Vec<String> = model.stored().map(|field| field.name.to_string()).collect();
let computed: Vec<String> = model
.computed()
.map(|field| field.name.to_string())
.collect();
assert_eq!(stored, ["title", "mask"]);
assert_eq!(computed, ["display_label", "checksum"]);
assert_eq!(stored.len() + computed.len(), model.fields.len());
}
#[test]
fn the_fallible_tier_is_the_one_that_says_so() {
assert!(!Tier::Stored.computed());
assert!(!Tier::Stored.fallible());
assert!(Tier::Computed.computed());
assert!(!Tier::Computed.fallible());
assert!(Tier::TryComputed.computed());
assert!(Tier::TryComputed.fallible());
}
#[test]
fn an_unpinned_field_is_stored_at_the_type_it_was_declared_with() {
let model = media();
let title = &model.fields[0];
let mask = &model.fields[1];
for kind in DatabaseKind::ALL {
assert_eq!(tight(title.pinned(kind)), "String", "{kind:?}");
}
assert_eq!(tight(mask.pinned(DatabaseKind::Sqlite)), "u32");
assert_eq!(tight(mask.pinned(DatabaseKind::Postgres)), "Mask");
assert_eq!(tight(mask.pinned(DatabaseKind::Mongo)), "Mask");
}
#[test]
fn the_databases_are_the_block_and_the_pins_together() {
assert_eq!(
media().databases(),
[DatabaseKind::Sqlite, DatabaseKind::Postgres],
"the pins alone"
);
let mut blocked = media();
blocked.persist = vec![selected(DatabaseKind::Mongo)];
assert_eq!(
blocked.databases(),
[
DatabaseKind::Sqlite,
DatabaseKind::Postgres,
DatabaseKind::Mongo
],
"the block adds one, and the order is the framework's"
);
let mut unpinned = media();
unpinned.fields[1].pins.clear();
unpinned.persist = vec![selected(DatabaseKind::Mysql)];
assert_eq!(
unpinned.databases(),
[DatabaseKind::Mysql],
"the block alone, for a declaration whose fields are all short-form"
);
}
#[test]
fn the_computed_error_defaults_to_the_boxed_refusal() {
assert_eq!(
tight(media().computed_error()),
tight(crate::model::boxed_error())
);
let mut declared = media();
declared.computed_error = Some(syn::parse_quote!(media::ComputeError));
assert_eq!(tight(declared.computed_error()), "media::ComputeError");
}
#[test]
fn the_enumeration_names_every_type_that_reaches_the_scope() {
let names: Vec<String> = media()
.emitted_types()
.iter()
.map(|declared| declared.name.to_string())
.collect();
assert_eq!(
names,
[
"MediaUnwrapError",
"MediaFields",
"MediaDerivations",
"MediaKind",
"MediaId",
"MediaKey",
"MediaSqliteRow",
"MediaPostgresRow",
"MediaSqliteCursor",
"MediaSqliteComparison",
"MediaPostgresCursor",
"MediaPostgresComparison",
"MediaOrderBy",
"MediaFilter",
"MediaGraphqlInput",
"MediaGraphqlOutput",
"MediaQueries"
]
);
}
#[test]
fn every_emitted_name_says_which_of_the_declarations_types_it_is() {
let roles: Vec<String> = media()
.emitted_types()
.iter()
.map(|declared| declared.role.to_string())
.collect();
assert_eq!(
roles,
[
"the refusal a wrong-variant unwrap answers with",
"the contract trait",
"the derivations trait",
"the discriminant",
"the address",
"the key type",
"the `sqlite` row",
"the `postgres` row",
"the `sqlite` cursor value",
"the `sqlite` comparison",
"the `postgres` cursor value",
"the `postgres` comparison",
"the order-by",
"the filter",
"the wire arguments",
"the wire output",
"the query unit"
]
);
}
#[test]
fn an_interface_with_nothing_to_select_declares_no_projection() {
let mut model = media();
model.fields.retain(|field| field.tier.computed());
model.persist = vec![selected(DatabaseKind::Sqlite)];
let names: Vec<String> = model
.emitted_types()
.iter()
.map(|declared| declared.name.to_string())
.collect();
assert!(!model.projects());
assert_eq!(
names,
[
"MediaUnwrapError",
"MediaFields",
"MediaDerivations",
"MediaGraphqlOutput"
],
"the wire OUTPUT is unconditional where the projection's names are not: every member has a wire \
face, so the sum over them is writable whatever a declaration stores"
);
}
#[test]
fn the_projection_takes_the_names_that_were_reserved_for_it() {
let interface = ident("Media");
assert_eq!(default_kind_name(&interface), "MediaKind");
assert_eq!(default_id_name(&interface), "MediaId");
assert_eq!(default_key_name(&interface), "MediaKey");
assert_eq!(
default_row_name(&interface, DatabaseKind::Sqlite),
"MediaSqliteRow"
);
let rendered = rendered(&media());
assert!(rendered.contains("enum MediaKind"), "{rendered}");
assert!(rendered.contains("enum MediaId"), "{rendered}");
assert!(rendered.contains("enum MediaKey"), "{rendered}");
assert!(rendered.contains("struct MediaSqliteRow"), "{rendered}");
assert!(rendered.contains("struct MediaPostgresRow"), "{rendered}");
}
#[test]
fn every_reserved_name_has_been_spent_on_its_emission() {
let interface = ident("Media");
assert_eq!(default_key_name(&interface), "MediaKey");
assert_eq!(default_output_name(&interface), "MediaGraphqlOutput");
assert_eq!(default_order_by_name(&interface), "MediaOrderBy");
assert_eq!(default_filter_name(&interface), "MediaFilter");
assert_eq!(default_input_name(&interface), "MediaGraphqlInput");
let rendered = rendered(&media());
for name in [
"MediaKey",
"MediaGraphqlOutput",
"MediaOrderBy",
"MediaFilter",
"MediaGraphqlInput",
] {
assert!(
rendered.contains(name),
"`{name}` was reserved and is emitted: {rendered}"
);
}
}
#[test]
fn the_contract_names_follow_the_interfaces_own() {
let interface = ident("Playable");
assert_eq!(default_fields_name(&interface), "PlayableFields");
assert_eq!(default_derivations_name(&interface), "PlayableDerivations");
assert_eq!(media().fields_name(), "MediaFields");
assert_eq!(media().derivations_name(), "MediaDerivations");
}
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 declared_trait(file: &syn::File, name: &str) -> Vec<String> {
all_items(file)
.into_iter()
.find_map(|item| match item {
syn::Item::Trait(item) if item.ident == name => Some(item),
_ => None,
})
.unwrap_or_else(|| panic!("`{name}` is declared"))
.items
.iter()
.filter_map(|item| match item {
syn::TraitItem::Fn(item) => Some(tight(&item.sig)),
_ => None,
})
.collect()
}
fn trait_impls(file: &syn::File) -> Vec<String> {
all_items(file)
.into_iter()
.filter_map(|item| match item {
syn::Item::Impl(item) => item
.trait_
.as_ref()
.map(|(path, _)| format!("{} for {}", tight(path), tight(&item.self_ty))),
_ => None,
})
.collect()
}
#[test]
fn the_contract_carries_the_stored_tier_and_the_derivations_the_computed_one() {
let file = emission(&media());
assert_eq!(
declared_trait(&file, "MediaFields"),
[
"fntitle(&self)->&::core::primitive::str",
"fnmask(&self)->Mask"
]
);
assert_eq!(
declared_trait(&file, "MediaDerivations"),
[
"fndisplay_label(&self)->String",
"fnchecksum(&self)->::core::result::Result<u64,::std::boxed::Box<dyn::core::error::Error+::\
core::marker::Send+::core::marker::Sync+'static>>"
]
);
}
#[test]
fn a_projection_follows_the_declared_type_and_the_copy_claim() {
let mut model = media();
model.fields.push(InterfaceField {
name: ident("caption"),
ty: syn::parse_quote!(Text),
tier: Tier::Stored,
marker: None,
copy: false,
pins: Vec::new(),
wire: None,
operands: Vec::new(),
members: Vec::new(),
});
assert_eq!(
declared_trait(&emission(&model), "MediaFields"),
[
"fntitle(&self)->&::core::primitive::str",
"fnmask(&self)->Mask",
"fncaption(&self)->&Text"
]
);
}
#[test]
fn a_member_answers_the_contract_by_reading_its_own_field() {
let rendered = rendered(&media());
assert!(
rendered.contains("impl MediaFields for Video"),
"{rendered}"
);
assert!(
rendered.contains("impl MediaFields for Audio"),
"{rendered}"
);
assert!(rendered.contains("&self.title"), "{rendered}");
assert!(rendered.contains("self.mask"), "{rendered}");
}
#[test]
fn the_interface_delegates_to_whichever_member_is_held() {
let rendered = rendered(&media());
assert!(
rendered.contains("impl MediaFields for Media"),
"{rendered}"
);
assert!(
rendered.contains("Self::Video(member) => <Video as MediaFields>::title(member)"),
"{rendered}"
);
assert!(
rendered.contains("Self::Audio(member) => <Audio as MediaFields>::mask(member)"),
"{rendered}"
);
}
#[test]
fn the_derivations_trait_is_declared_and_implemented_by_nobody() {
let impls = trait_impls(&emission(&media()));
assert!(
!impls.iter().any(|item| item.contains("MediaDerivations")),
"{impls:?}"
);
assert_eq!(
impls
.iter()
.filter(|item| item.starts_with("MediaFields for"))
.count(),
3,
"two members and the interface itself: {impls:?}"
);
}
#[test]
fn the_membership_ties_are_emitted_before_anything_reads_a_column() {
let rendered = rendered(&media());
let at = |needle: &str| {
rendered
.find(needle)
.unwrap_or_else(|| panic!("`{needle}` is emitted: {rendered}"))
};
let membership = at("transform::implements::<Video, Media>");
let stored = at("transform::stores_rows::<Video>");
let wire = at("transform::has_a_wire_face::<Video>");
let contract = at("impl MediaFields for Video");
assert!(membership < stored, "membership leads: {rendered}");
assert!(stored < wire);
assert!(wire < contract, "and every tie precedes the columns");
}
#[test]
fn only_the_enumerated_types_land_in_the_declaring_scope() {
let file = emission(&media());
let scoped: Vec<String> = file
.items
.iter()
.filter_map(|item| match item {
syn::Item::Struct(item) => Some(item.ident.to_string()),
syn::Item::Trait(item) => Some(item.ident.to_string()),
syn::Item::Enum(item) => Some(item.ident.to_string()),
_ => None,
})
.collect();
assert_eq!(
scoped,
media()
.emitted_types()
.iter()
.map(|declared| declared.name.to_string())
.collect::<Vec<_>>()
);
}
#[test]
fn the_contract_mirrors_the_declarations_visibility() {
let mut model = media();
model.vis = syn::parse_quote!(pub(crate));
let rendered = rendered(&model);
assert!(
rendered.contains("pub(crate) trait MediaFields"),
"{rendered}"
);
assert!(
rendered.contains("pub(crate) trait MediaDerivations"),
"{rendered}"
);
assert!(!rendered.contains("pub trait"), "{rendered}");
}
#[test]
fn the_declared_computed_error_types_the_fallible_derivation() {
let mut model = media();
model.computed_error = Some(syn::parse_quote!(media::ComputeError));
let file = emission(&model);
assert_eq!(
declared_trait(&file, "MediaDerivations")[1],
"fnchecksum(&self)->::core::result::Result<u64,media::ComputeError>"
);
assert!(
rendered(&model).contains("[`media::ComputeError`]"),
"the `# Errors` note names it too"
);
}
#[test]
fn every_pin_is_discharged_at_the_row_that_has_to_satisfy_it() {
let emitted = tight(media().equations());
for (member, database, field, backend, ty) in [
("video", "sqlite", "title", "Sqlite", "String"),
("video", "sqlite", "mask", "Sqlite", "u32"),
("video", "postgres", "mask", "Postgres", "Mask"),
("audio", "postgres", "title", "Postgres", "String"),
] {
let equation = format!(
"fn_{member}_{database}_{field}(row:&<{Member}as::ingraph::__private::transform::Record<::\
ingraph::__private::sqlx::{backend}>>::Row)->&{ty}{{&row.{field}}}",
Member = if member == "video" { "Video" } else { "Audio" },
);
assert!(emitted.contains(&equation), "{equation}\n{emitted}");
}
assert!(
!emitted.contains("display_label"),
"a computed field has no column to equate: {emitted}"
);
assert!(
!emitted.contains("if_mysql"),
"and a database nothing named is not checked: {emitted}"
);
}
#[test]
fn every_equation_is_named_out_of_the_dead_code_lint() {
let emitted = tight(media().equations());
let names: Vec<&str> = emitted
.match_indices("fn")
.map(|(at, _)| {
let rest = &emitted[at + 2..];
&rest[..rest.find('(').expect("a function takes arguments")]
})
.collect();
assert_eq!(names.len(), 8, "two members, two fields, two databases");
assert!(names.iter().all(|name| name.starts_with('_')), "{names:?}");
}
#[test]
fn the_equations_ride_the_gate_of_the_database_they_name() {
let emitted = tight(media().equations());
let at = |needle: &str| {
emitted
.find(needle)
.unwrap_or_else(|| panic!("`{needle}` is emitted: {emitted}"))
};
assert!(at("gate::if_sqlite!") < at("fn_video_sqlite_title"));
assert!(at("fn_audio_sqlite_mask") < at("gate::if_postgres!"));
assert!(at("fn_video_postgres_title") > at("gate::if_postgres!"));
}
#[test]
fn an_interface_about_no_database_writes_no_equation() {
let mut unpinned = media();
unpinned.fields[1].pins.clear();
assert!(tight(unpinned.equations()).is_empty());
unpinned.persist = vec![selected(DatabaseKind::Mongo)];
let emitted = tight(unpinned.equations());
assert!(emitted.contains("gate::if_mongo!"), "{emitted}");
assert!(
emitted.contains(
"fn_video_mongo_mask(row:&<Videoas::ingraph::__private::transform::Record<::\
ingraph::__private::comparison::mongo::Mongo>>::Row)->&Mask"
),
"an unpinned field is checked at the DOMAIN type, and mongo's backend is not sqlx's: {emitted}"
);
}
#[test]
fn the_expansion_implements_only_the_traits_it_declared_or_the_engine_publishes() {
let declared: Vec<String> = media()
.emitted_types()
.iter()
.map(|item| item.name.to_string())
.collect();
let engine = [
"::ingraph::__private::interface::InterfaceKind",
"::ingraph::__private::sqlx::FromRow",
"::ingraph::__private::cursor::CursorValue",
"::ingraph::__private::comparison::sql::Carrier",
"::ingraph::__private::comparison::ComplexComparison",
"::ingraph::__private::graphql::ToSubjectPath",
"::ingraph::__private::async_graphql::InputType",
"::ingraph::__private::async_graphql::InputObjectType",
"::ingraph::__private::async_graphql::OneofObjectType",
"::ingraph::__private::async_graphql::OutputType",
"::ingraph::__private::async_graphql::InterfaceType",
"::ingraph::__private::async_graphql::resolver_utils::ContainerType",
"::ingraph::__private::transform::Graphql",
"::ingraph::__private::transform::GraphqlInput",
"::ingraph::__private::transform::GraphqlOutput",
"::ingraph::__private::comparison::TryFromFilter",
];
for implemented in trait_impls(&emission(&media())) {
let (implemented_trait, _) = implemented
.split_once(" for ")
.expect("an impl names a trait and a self type");
let engine_seam = engine
.iter()
.any(|seam| implemented_trait.starts_with(seam));
assert!(
declared.iter().any(|name| name == implemented_trait)
|| implemented_trait.starts_with("::core::")
|| engine_seam,
"`{implemented}` is none of this expansion's own, `core`'s, or the engine's published seams"
);
}
}
#[test]
fn every_framework_path_is_rooted_at_the_declared_crate() {
let mut model = media();
model.krate = syn::parse_quote!(shim::ingraph);
let emitted = tight(model.emit());
assert!(emitted.contains("shim::ingraph::__private::transform::implements"));
assert!(emitted.contains("shim::ingraph::__private::gate::if_sqlite"));
assert!(emitted.contains("shim::ingraph::__private::sqlx::Sqlite"));
assert_eq!(
emitted.matches("__private").count(),
emitted.matches("shim::ingraph::__private").count(),
"every shelf reach is rooted at the DECLARED crate: {emitted}"
);
assert!(
!emitted.contains("shim::ingraph::transform"),
"and none of them steps past the shelf into a real module path: {emitted}"
);
}
#[test]
fn a_member_block_moves_the_access_and_leaves_the_method_alone() {
let model = media();
let contract = tight(model.contract());
let equations = tight(model.equations());
assert!(
contract.contains(
"implMediaFieldsforAudio{#[inline]fntitle(&self)->&::core::primitive::str{&\
self.title}#[inline]fnmask(&self)->Mask{self.flags}}"
),
"the method is `mask` and the access is `flags`: {contract}"
);
assert!(
contract.contains(
"implMediaFieldsforVideo{#[inline]fntitle(&self)->&::core::primitive::str{&\
self.title}#[inline]fnmask(&self)->Mask{self.mask}}"
),
"and a member that renamed nothing reads its own name: {contract}"
);
assert!(
contract.contains("Self::Audio(member)=><AudioasMediaFields>::mask(member)"),
"the delegation calls the CONTRACT's name, which no member block moves: {contract}"
);
assert!(
equations.contains(
"fn_audio_sqlite_mask(row:&<Audioas::ingraph::__private::transform::Record<\
::ingraph::__private::sqlx::Sqlite>>::Row)->&u32{&row.flags}"
),
"and the row is read at the same name the struct is: {equations}"
);
}
#[test]
fn one_resolver_answers_what_each_member_calls_a_field() {
let model = media();
let mask = &model.fields[1];
assert_eq!(*mask.column(&ident("Audio")), "flags");
assert_eq!(
*mask.column(&ident("Video")),
"mask",
"the default is the interface's own name"
);
assert_eq!(
*model.fields[0].column(&ident("Audio")),
"title",
"and a field no member renamed answers alike for every one of them"
);
}
#[test]
fn the_projection_carries_the_shared_columns_at_the_pinned_types() {
let rendered = rendered(&media());
assert!(
rendered.contains(
"pub struct MediaSqliteRow {\n __ig_kind__: MediaKind,\n id: MediaId,\n title: String,\n mask: u32,\n}"
),
"{rendered}"
);
assert!(
rendered.contains(
"pub struct MediaPostgresRow {\n __ig_kind__: MediaKind,\n id: MediaId,\n title: String,\n mask: Mask,\n}"
),
"the unpinned database keeps the domain type: {rendered}"
);
}
#[test]
fn a_derived_value_has_no_column_to_project() {
let rendered = rendered(&media());
assert!(!rendered.contains("display_label: "), "{rendered}");
assert!(!rendered.contains("checksum: "), "{rendered}");
}
#[test]
fn the_discriminant_word_is_the_members_own() {
let emitted = tight(media().projection());
assert!(emitted.contains(r#"Self::Video=>"video","#), "{emitted}");
assert!(emitted.contains(r#"Self::Audio=>"audio","#), "{emitted}");
assert!(
emitted.contains(r#"constINTERFACE:&'static::core::primitive::str="Media";"#),
"{emitted}"
);
}
#[test]
fn the_binding_rides_the_gate_of_the_database_it_names() {
let emitted = tight(media().bindings());
let at = |needle: &str| {
emitted
.find(needle)
.unwrap_or_else(|| panic!("`{needle}` is emitted: {emitted}"))
};
assert!(at("gate::if_sqlite!") < at("typeRow=MediaSqliteRow;"));
assert!(at("typeRow=MediaSqliteRow;") < at("gate::if_postgres!"));
assert!(at("gate::if_postgres!") < at("typeRow=MediaPostgresRow;"));
assert!(!emitted.contains("if_mysql"), "{emitted}");
}
#[test]
fn each_arm_carries_what_its_member_calls_the_shared_column() {
let emitted = tight(media().bindings());
assert!(
emitted.contains(
r#"InterfaceArm::new(MediaKind::Audio,&[::ingraph::__private::interface::InterfaceColumn::new(::ingraph::__private::field::FieldName::new("title"),::ingraph::__private::field::FieldName::new("title")),::ingraph::__private::interface::InterfaceColumn::new(::ingraph::__private::field::FieldName::new("mask"),::ingraph::__private::field::FieldName::new("flags")),])"#
),
"{emitted}"
);
}
#[test]
fn the_address_is_the_members_own_and_never_a_copy() {
let emitted = tight(media().bindings());
assert!(
emitted.contains(
"MediaKind::Video=><<Videoas::ingraph::__private::transform::Record<::ingraph::__private::\
sqlx::Sqlite>>::Rowas::ingraph::__private::query::sql::SqlQuery<::ingraph::__private::sqlx::\
Sqlite>>::ADDRESS,"
),
"{emitted}"
);
}
#[test]
fn an_interface_with_no_projection_has_no_binding() {
let mut model = media();
model.fields.retain(|field| field.tier.computed());
model.persist = vec![selected(DatabaseKind::Sqlite)];
assert!(tight(model.projection()).is_empty());
assert!(tight(model.bindings()).is_empty());
}
#[test]
fn the_address_carries_each_members_own_id_through_the_projection() {
let emitted = tight(media().projection());
assert!(
emitted.contains("Video(<Videoas::ingraph::__private::transform::Identifiable>::Id)"),
"{emitted}"
);
assert!(
emitted.contains("Audio(<Audioas::ingraph::__private::transform::Identifiable>::Id)"),
"{emitted}"
);
assert!(
emitted.contains("Self::Video(_)=>MediaKind::Video,"),
"and reading the kind back off the address is what keeps the pair coherent: {emitted}"
);
}
#[test]
fn the_key_carries_each_members_own_key_through_the_projection() {
let emitted = tight(media().projection());
assert!(
emitted.contains("Video(<Videoas::ingraph::__private::transform::Transformer>::Key)"),
"{emitted}"
);
assert!(
emitted.contains("Audio(<Audioas::ingraph::__private::transform::Transformer>::Key)"),
"{emitted}"
);
assert_eq!(
emitted.matches("Self::Video(_)=>MediaKind::Video,").count(),
2,
"both addresses read the discriminant back off themselves: {emitted}"
);
assert_eq!(
emitted.matches("Self::Audio(_)=>MediaKind::Audio,").count(),
2,
"{emitted}"
);
}
#[test]
fn nothing_decodes_a_key_out_of_a_row() {
let emitted = tight(media().projection());
assert!(
emitted.contains("FromRow<'a,__INGRAPH_ROW__>forMediaSqliteRow"),
"the row is decoded: {emitted}"
);
assert!(
!emitted.contains("forMediaKey"),
"and the key is not: {emitted}"
);
assert!(
!emitted.contains("MediaKey::Video("),
"nor is one built anywhere — the type is the vocabulary and nothing spends it yet: {emitted}"
);
}
#[test]
fn the_decode_reads_the_discriminant_before_the_address() {
let emitted = tight(media().projection());
let at = |needle: &str| {
emitted
.find(needle)
.unwrap_or_else(|| panic!("`{needle}` is emitted: {emitted}"))
};
assert!(at("let__ig_kind__=<MediaKindas") < at("letid=match__ig_kind__{"));
assert!(at("letid=match__ig_kind__{") < at("lettitle:String=__row.try_get"));
assert!(
emitted.contains("MediaKind::Audio=>MediaId::Audio(__row.try_get(__ingraph_id)?),"),
"{emitted}"
);
}
#[test]
fn the_discriminant_wears_the_fence_and_the_address_does_not() {
let emitted = tight(media().projection());
assert!(emitted.contains("__ig_kind__:MediaKind,"), "{emitted}");
assert!(emitted.contains("id:MediaId,"), "{emitted}");
assert!(
!emitted.contains("kind:MediaKind,"),
"a bare `kind` would compete with a field a declaration may promise: {emitted}"
);
}
#[test]
fn the_filter_carries_the_shared_columns_and_no_derived_one() {
let emitted = tight(media().wire());
assert!(emitted.contains("pubstructMediaFilter{"), "{emitted}");
assert!(
emitted.contains("title:::core::option::Option<"),
"{emitted}"
);
assert!(
emitted.contains("mask:::core::option::Option<"),
"{emitted}"
);
assert!(
!emitted.contains("display_label:") && !emitted.contains("checksum:"),
"a derived value is statically absent: {emitted}"
);
assert!(emitted.contains("pubfnwith_title(mutself,"), "{emitted}");
assert!(emitted.contains("pubconstfnmask_ref(&self)"), "{emitted}");
}
#[test]
fn the_filter_and_the_predicate_ask_one_question_of_a_type() {
let model = media();
let filter = tight(model.wire());
let asked = tight(
model.filter_of(
model
.stored()
.next()
.expect("the fixture's first stored field is `title`"),
),
);
assert!(
filter.contains(&format!("title:::core::option::Option<{asked}>")),
"{filter}"
);
assert!(
tight(model.page()).contains(&asked),
"the predicate asks the same projection the filter does"
);
}
#[test]
fn the_arguments_are_the_lane_and_carry_no_member_it_cannot_spend() {
let emitted = tight(media().wire());
assert!(emitted.contains("pubstructMediaGraphqlInput{"), "{emitted}");
assert!(
emitted.contains("order:::std::vec::Vec<MediaOrderBy>,"),
"{emitted}"
);
assert!(
emitted.contains("filter:::core::option::Option<MediaFilter>,"),
"{emitted}"
);
for member in ["first", "last", "after", "before"] {
assert!(
emitted.contains(&format!("{member}:::core::option::Option<")),
"{member}: {emitted}"
);
}
assert!(
!emitted.contains("limit:::core::option::Option<")
&& !emitted.contains("skip:::core::option::Option<"),
"a member no method could spend is an argument object promising a query the engine refuses: \
{emitted}"
);
assert!(
emitted.contains("after:::core::option::Option<::std::string::String>,"),
"a cursor is the STRING a client holds — the typed slot is per database and this object is \
not: {emitted}"
);
}
#[test]
fn the_crossing_is_stated_at_the_dialect_its_binding_already_names() {
let emitted = tight(media().bindings());
assert!(
emitted.contains(
"impl::ingraph::__private::comparison::TryFromFilter<MediaFilter>for \
MediaSqliteComparison<::ingraph::__private::sqlx::Sqlite>"
) || emitted.contains(
"impl::ingraph::__private::comparison::TryFromFilter<MediaFilter>forMediaSqliteComparison<::ingraph::__private::sqlx::Sqlite>"
),
"{emitted}"
);
assert!(
emitted.contains("::ingraph::__private::gate::if_sqlite!"),
"and it rides the gate the rest of the engine face does: {emitted}"
);
let mut bare = media();
bare.fields.retain(|field| field.tier.computed());
assert!(
tight(bare.bindings()).is_empty(),
"a declaration with nothing stored projects nothing and crosses nothing"
);
}
#[test]
fn a_declared_operand_leg_replaces_the_stored_types_own() {
let emitted = tight(media().bindings());
assert!(
emitted.contains("try_from_filter_with(__ingraph_held,narrow)"),
"{emitted}"
);
assert!(
emitted.contains("::ingraph::__private::comparison::TryFromFilter<"),
"and the Postgres half takes the trait crossing instead: {emitted}"
);
assert!(
emitted.contains("::core::option::Option::None=>::core::default::Default::default()"),
"a column the client said nothing about is the EMPTY comparison: {emitted}"
);
}
#[test]
fn the_crossing_answers_with_the_cell_its_database_named() {
let boxed = tight(media().bindings());
assert!(
boxed.contains("typeError=::std::boxed::Box<dyn::core::error::Error+::core::marker::Send+::core::marker::Sync+'static>"),
"{boxed}"
);
let mut declared = media();
declared.operand_errors = vec![super::InterfaceError {
kind: DatabaseKind::Sqlite,
error: syn::parse_quote!(crate::TooWide),
}];
let emitted = tight(declared.bindings());
assert!(emitted.contains("typeError=crate::TooWide;"), "{emitted}");
assert!(
emitted.contains("typeError=::std::boxed::Box<"),
"and the database with no cell keeps the boxed refusal: {emitted}"
);
}
fn selected(kind: DatabaseKind) -> InterfaceDatabase {
InterfaceDatabase {
kind,
aliases: crate::model::AliasOptions::default(),
}
}
fn reeled() -> InterfaceModel {
let mut model = media();
model.fields.push(InterfaceField {
name: ident("marks"),
ty: syn::parse_quote!(Vec<u64>),
tier: Tier::Stored,
marker: Some(crate::model::Marker::Framework(
crate::model::FrameworkMarker {
label: crate::model::Label::List,
element: Some(crate::model::Label::Scalar),
},
)),
copy: false,
pins: vec![Pin {
kind: DatabaseKind::Sqlite,
stored: Some(syn::parse_quote!(i64)),
}],
wire: None,
operands: Vec::new(),
members: Vec::new(),
});
model
}
#[test]
fn a_collection_pins_the_list_at_the_row_and_the_element_at_the_crossing() {
let model = reeled();
let equations = tight(model.equations());
assert!(
equations.contains("fn_video_sqlite_marks(row:&<Videoas"),
"the row equation is written for the collection at all: {equations}"
);
assert!(
equations.contains(">::Row)->&::std::vec::Vec<i64>"),
"and it takes the LIST: {equations}"
);
assert!(
equations.contains(">::Row)->&u32"),
"where a scalar pin is unchanged at both sites: {equations}"
);
assert!(
equations.contains("ToDatabaseComparison<i64,"),
"the comparison reading of the same pin is keyed on the ELEMENT: {equations}"
);
assert!(
equations.contains(
"ToDatabaseComparison<<Vec<u64>as::ingraph::__private::state::State<::ingraph::__private::state::Extracted<::ingraph::__private::state::Inner>>>::Output,"
),
"an UNPINNED collection is keyed on its element projection: {equations}"
);
assert!(
!equations.contains("Vec<Vec<u64>>"),
"and never on a list of lists: {equations}"
);
}
#[test]
fn the_word_is_asserted_against_every_members_own_collection_kind() {
let emitted = tight(reeled().equations());
for member in ["video", "audio"] {
assert!(
emitted.contains(&format!("fn_{member}_sqlite_marks_collection(")),
"{emitted}"
);
}
assert!(
emitted.contains("__ingraph_held.marks_ref()"),
"it reads the member's column through the comparison's borrow face: {emitted}"
);
assert!(
emitted.contains("::ingraph::__private::marker::ListMarker<"),
"at the type the INTERFACE's word resolves to: {emitted}"
);
assert!(
!emitted.contains("_mask_collection"),
"and a scalar pin gets none: {emitted}"
);
}
#[test]
fn a_collection_is_no_column_of_the_projection() {
let model = reeled();
let projection = tight(model.projection());
let binding = tight(model.bindings());
let page = tight(model.page());
assert!(
projection.contains("title:String,"),
"the scalar columns are still the row's: {projection}"
);
assert!(
!projection.contains("marks"),
"and the collection is not on the row, nor in its decode: {projection}"
);
let arms = binding
.split_once("constARMS")
.and_then(|(_, rest)| rest.split_once("];"))
.map(|(arms, _)| arms.to_owned())
.expect("the binding states its arms");
assert!(
!arms.contains("marks"),
"no arm SELECTS it — the arms' column list is `projected()`: {arms}"
);
assert!(
binding.contains("fncollections<"),
"and the predicate reaches it per arm instead, at the member's own edge table: {binding}"
);
assert!(
!page.contains("Marks("),
"and no cursor slot holds it: {page}"
);
assert!(
model.projects(),
"an interface promising one is still a projection — the union has the tail to select"
);
}
#[test]
fn a_collection_is_an_order_term_and_its_subject_is_the_edge() {
let emitted = tight(reeled().ordering());
assert!(
emitted.contains("Marks(::ingraph::__private::graphql::OrderDirection)"),
"{emitted}"
);
assert!(
emitted
.contains("Self::Marks(__ingraph_direction)=>::ingraph::__private::cursor::OrderTerm::edge("),
"the collection's term is EDGE: {emitted}"
);
assert!(
emitted
.contains("Self::Title(__ingraph_direction)=>::ingraph::__private::cursor::OrderTerm::new("),
"and a scalar's is unchanged: {emitted}"
);
assert!(
!emitted.contains("OrderTerm::array"),
"an interface never mints an array term — the storage form is the MEMBER's: {emitted}"
);
}
#[test]
fn a_platform_mark_moves_the_synthetic_words_and_ends_the_silence() {
let mut model = media();
model.prefix = EmissionPrefix::new("__mg");
for kind in [DatabaseKind::Sqlite, DatabaseKind::Postgres] {
assert_eq!(model.kind_word(kind), "__mg_kind__");
assert_eq!(model.source_word(kind), "__mg_union__");
assert!(
!model.mints_the_default_words(kind),
"the engine still believes `__ig_kind__`, so the expansion has to say otherwise",
);
}
}
#[test]
fn a_database_block_outranks_the_models_own_mark() {
let mut model = media();
model.prefix = EmissionPrefix::new("__mg");
model.persist = vec![crate::interface::InterfaceDatabase {
kind: DatabaseKind::Sqlite,
aliases: crate::model::AliasOptions {
prefix: Some(String::from("__mine")),
depth: None,
},
}];
assert_eq!(model.kind_word(DatabaseKind::Sqlite), "__mine_kind__");
assert_eq!(
model.kind_word(DatabaseKind::Postgres),
"__mg_kind__",
"the database beside it named nothing, so it takes the model's seat",
);
}