use serde_json::{json, Value}; use super::*; use crate::records::{self, RecordError}; const FILED: &str = include_str!("../../tests/fixtures/definitions-parity-7/computed_parity.json"); /// RULE: A running opening gathers one table-wide value without a backlink, so pooled balances seed every ordered row instead of changing the opening for each row. #[test] fn running_opening_validates_a_table_wide_aggregate_without_a_backlink() { let base = table("pooled_run", None, json!([ {"key":"name", "type":"text"}, {"key":"position", "type":"number"}, {"key":"amount", "type":"amount"} ])); let mut value = serde_json::to_value(base).unwrap(); value["sort"] = json!({"column":"position"}); value["columns"].as_array_mut().unwrap().push(json!({ "key":"balance", "type":"amount", "computed":{"running":{"column":"amount", "opening":{"rollup":{"table":"opening_pool", "op":"sum", "column":"amount", "where":{"column":"pooled", "values":["true"]}}}}} })); let definition = TableDefinition::from_json(&value.to_string()).expect("a global opening needs no backlink"); definition.validate().unwrap(); let source = table("opening_pool", None, json!([ {"key":"name", "type":"text"}, {"key":"amount", "type":"amount"}, {"key":"pooled", "type":"bool"} ])); validate_across(&[&definition,&source]).unwrap(); value["columns"][3]["computed"]["running"]["opening"]["rollup"]["column"] = json!("name"); let wrong = parse(&value); assert!(validate_across(&[&wrong,&source]).is_err()); value["columns"][3]["computed"]["running"]["opening"]["rollup"]["column"] = json!("amount"); value["columns"][3]["computed"]["running"]["opening"]["rollup"]["link"] = json!("movement"); assert!(TableDefinition::from_json(&value.to_string()).is_err(), "a table-wide opening never selects a per-row backlink"); assert!(serde_json::from_value::(json!({"rollup":{"table":"opening_pool", "op":"sum", "column":"amount"}})).is_err(), "ordinary row-linked rollups keep their existing wire contract"); } /// RULE: A running says its opening above an ungrouped list in words of its own (`opening_label`): blank words or a grouped list, which has no one first row, are refused; the core says the line, amount then words, and nothing at nothing. #[test] fn a_running_opening_label_is_said_above_an_ungrouped_list() { let base = table("ahead_run", None, json!([ {"key":"name", "type":"text"}, {"key":"position", "type":"number"}, {"key":"amount", "type":"amount"} ])); let mut value = serde_json::to_value(base).unwrap(); value["sort"] = json!({"column":"position"}); value["columns"].as_array_mut().unwrap().push(json!({ "key":"balance", "type":"amount", "computed":{"running":{"column":"amount", "opening":0, "opening_label":"held today"}} })); let definition = parse(&value); definition.validate().expect("an opening said in words"); assert_eq!(records::opening_column(&definition), Some(("balance", "held today"))); let head = records::opening_head(&definition, &json!(12_000_000), Some("INR"), crate::records::page::Words::shipped()).expect("a line"); assert_eq!(head.lines, vec!["\u{20B9}1,20,000 held today".to_string()]); assert_eq!(head.value, Value::Null, "the list's one section is no group's"); assert!(records::opening_head(&definition, &json!(0), Some("INR"), crate::records::page::Words::shipped()).is_none(), "nothing held says nothing"); let mut blank = value.clone(); blank["columns"][3]["computed"]["running"]["opening_label"] = json!(" "); assert!(parse(&blank).validate().is_err(), "blank words"); let mut grouped = value.clone(); grouped["group"] = json!({"column":"name", "sections":[]}); assert!(parse(&grouped).validate().is_err(), "a grouped list has no one first row"); } /// The filed invoice, as JSON a test can bend. fn invoice() -> Value { serde_json::from_str(FILED).expect("the filed fixture is JSON") } fn parse(value: &Value) -> TableDefinition { serde_json::from_value(value.clone()).expect("parses") } /// A user table of the columns given. fn table(id: &str, date: Option<&str>, columns: Value) -> TableDefinition { let title = columns[0]["key"].clone(); let table = parse(&json!({ "id": id, "name": id, "plural": id, "picture": null, "builtin": false, "engine": null, "columns": columns, "title": title, "date": date, "project": null, "order": null, "slip": { "title": title, "subtitle": null, "trailing": null, "photo": null, "toggle": null }, "tile": { "face": "slip-list" }, "page": [{ "heading": null, "columns": [title] }], "instructions": "A fixture." })); table.validate().unwrap_or_else(|why| panic!("{id}: {why}")); table } /// The tables the filed invoice reads: a person, its lines and its payments. fn beside() -> Vec { vec![ table("person", None, json!([{ "key": "name", "type": "text" }])), table( "invoice_line", None, json!([ { "key": "what", "type": "text" }, { "key": "invoice", "type": "link", "link_to": "invoice" } ]), ), table( "payment", Some("paid_on"), json!([ { "key": "note", "type": "text" }, { "key": "invoice", "type": "link", "link_to": "invoice" }, { "key": "amount", "type": "amount" }, { "key": "status", "type": "choice", "choices": ["pending", "posted"] }, { "key": "paid_on", "type": "date" } ]), ), ] } /// The filed invoice with one column's `computed` replaced, validated alone. fn alone(column: &str, computed: Value) -> Result<(), DefinitionError> { let mut value = invoice(); let columns = value["columns"].as_array_mut().unwrap(); let at = columns.iter().position(|c| c["key"] == column).expect("a filed column"); columns[at]["computed"] = computed; parse(&value).validate() } /// The filed invoice with one column's `computed` replaced, checked beside /// the tables it reads. fn across(column: &str, computed: Value, others: Vec) -> Result<(), DefinitionError> { let mut value = invoice(); let columns = value["columns"].as_array_mut().unwrap(); let at = columns.iter().position(|c| c["key"] == column).expect("a filed column"); columns[at]["computed"] = computed; let invoice = parse(&value); invoice.validate()?; let mut all: Vec<&TableDefinition> = others.iter().collect(); all.push(&invoice); validate_across(&all) } /// RULE: Existing computed definitions preserve their validated values and wire form as the language grows, so adding a shape never breaks an installed tool. #[test] fn existing_computed_shapes_decode_validate_and_round_trip() { let definition = TableDefinition::from_json(FILED).expect("the filed definition decodes"); definition.validate().expect("the filed definition validates"); assert_eq!(definition.to_json(), FILED.trim_end()); let others = beside(); let mut all: Vec<&TableDefinition> = others.iter().collect(); all.push(&definition); validate_across(&all).expect("valid beside the tables it reads"); for (op, summary) in [ (RollupOp::Count, Some(SummaryOp::Count)), (RollupOp::Sum, Some(SummaryOp::Sum)), (RollupOp::Min, Some(SummaryOp::Min)), (RollupOp::Max, Some(SummaryOp::Max)), (RollupOp::First, None), (RollupOp::Latest, None), (RollupOp::Average, None), ] { assert_eq!(rollup_summary(op), summary); } } /// RULE: The computed format is closed — two shapes in one key, an empty key, an unknown shape, op or inner key do not parse, so a tool file never grows into a programming language. #[test] fn nothing_outside_the_closed_shapes_parses() { let lookup = json!({ "through": "customer", "column": "name" }); for bad in [ json!({}), json!({ "lookup": lookup, "formula": { "op": "sum", "of": ["net", "tax"] } }), json!({ "case": { "column": "kind" } }), json!({ "expression": "net + tax" }), json!("net + tax"), json!({"running":{"column":"net"}}), json!({"running":{"column":"net","opening":true}}), json!({"running":{"column":"net","opening":0,"code":"net + tax"}}), json!({"previous":{"column":"net","offset":2}}), json!({ "lookup": { "via": "customer", "column": "name" } }), json!({ "lookup": { "through": "customer", "column": "name", "else": "x" } }), json!({ "formula": { "op": "add", "of": ["net", "tax"] } }), json!({ "formula": { "op": "sum", "of": ["net", 1] } }), json!({ "rollup": { "table": "payment", "link": "invoice", "op": "median", "column": "amount" } }), json!({ "rollup": { "table": "payment", "link": "invoice", "op": "count", "where": { "status": "posted" } } }), ] { let mut value = invoice(); value["columns"][5]["computed"] = bad.clone(); assert!( TableDefinition::authored(&value).is_err(), "{bad} was accepted" ); } } /// RULE: A computed column is the core's to work out — it cannot be required, defaulted, secret or declared writable, and a create or a patch naming it is refused, so no device ever stores a value that disagrees with its sources. #[test] fn a_computed_column_is_read_only_and_no_write_names_it() { for (key, held) in [ ("readonly", json!(false)), ("required", json!(true)), ("default", json!(100)), ] { let mut value = invoice(); value["columns"][6][key] = held; assert!( matches!( parse(&value).validate(), Err(DefinitionError::Conflict { ref slot, .. }) if slot == "columns.total.computed" ), "{key} sat beside computed" ); } let definition = parse(&invoice()); assert!(matches!( records::validate_create(&definition, &json!({ "title": "March", "total": 100 })), Err(RecordError::Computed { ref column }) if column == "total" )); for patch in [json!({ "total": 100 }), json!({ "total": null })] { assert!(matches!( records::validate_patch(&definition, &patch), Err(RecordError::Computed { ref column }) if column == "total" )); } records::validate_create(&definition, &json!({ "title": "March", "net": 100 })) .expect("the stored columns still write"); } /// RULE: A computed shape reads only what suits it — a lookup goes through a single link, sum, difference and sign read numbers or amounts of the column's own type, join reads words into a text, count takes no column and is a number. #[test] fn a_computed_shape_names_columns_of_the_right_type_in_its_own_table() { let slot_of = |result: Result<(), DefinitionError>| match result.expect_err("refused") { DefinitionError::WrongColumnType { slot, .. } | DefinitionError::UnknownColumn { slot, .. } | DefinitionError::Requires { slot, .. } | DefinitionError::Conflict { slot, .. } | DefinitionError::UnknownChoice { slot, .. } | DefinitionError::EmptyAt(slot) => slot, other => panic!("refused another way: {other}"), }; for (column, computed, slot) in [ ("customer_name", json!({ "lookup": { "through": "title", "column": "name" } }), "lookup.through"), ("customer_name", json!({ "lookup": { "through": "gone", "column": "name" } }), "lookup.through"), ("total", json!({ "formula": { "op": "sum", "of": ["net"] } }), "formula.of"), ("total", json!({ "formula": { "op": "sum", "of": ["net", "title"] } }), "formula.of"), ("total", json!({ "formula": { "op": "difference", "of": ["net", "tax", "tax"] } }), "formula.of"), ("total", json!({ "formula": { "op": "signed", "of": ["net"] } }), "formula.flip_when"), ("total", json!({ "formula": { "op": "signed", "of": ["net"], "flip_when": { "column": "kind", "values": ["gift"] } } }), "formula.flip_when.values"), ("total", json!({ "formula": { "op": "signed", "of": ["net"], "flip_when": { "column": "kind", "values": [] } } }), "formula.flip_when.values"), ("total", json!({ "formula": { "op": "sign", "of": ["net"], "flip_when": { "column": "kind", "values": ["refund"] } } }), "formula.op"), ("total", json!({ "formula": { "op": "sum", "of": ["net", "tax"], "flip_when": { "column": "kind", "values": ["refund"] } } }), "formula.flip_when"), ("total", json!({ "formula": { "op": "sum", "of": ["net", "tax"], "separator": "+" } }), "formula.separator"), ("total", json!({ "formula": { "op": "join", "of": ["title", "kind"] } }), "formula.op"), ("label", json!({ "formula": { "op": "join", "of": ["title", "net"] } }), "formula.of"), ("label", json!({ "formula": { "op": "sum", "of": ["net", "tax"] } }), "formula.op"), ("line_count", json!({ "rollup": { "table": "invoice_line", "link": "invoice", "op": "count", "column": "what" } }), "rollup.column"), ("label", json!({ "rollup": { "table": "invoice_line", "link": "invoice", "op": "count" } }), "rollup.op"), ("paid", json!({ "rollup": { "table": "payment", "link": "invoice", "op": "sum" } }), "rollup.column"), ("label", json!({ "rollup": { "table": "payment", "link": "invoice", "op": "sum", "column": "amount" } }), "rollup.op"), ("paid", json!({ "rollup": { "table": "payment", "link": "invoice", "op": "sum", "column": "amount", "by": "paid_on" } }), "rollup.by"), ("paid", json!({ "rollup": { "table": "payment", "link": "invoice", "op": "sum", "column": "amount", "where": { "column": "status", "values": [] } } }), "rollup.where.values"), ] { assert_eq!( slot_of(alone(column, computed.clone())), format!("columns.{column}.computed.{slot}"), "{computed}" ); } } /// RULE: What a lookup or a rollup names in another table must be there and fit — the table, a link pointing back, a column of the computed column's own type, a where the other table can read, and a date or `by` for first and latest. #[test] fn a_lookup_and_a_rollup_fit_the_tables_they_read() { let sum = |patch: Value| { let mut rollup = json!({ "table": "payment", "link": "invoice", "op": "sum", "column": "amount" }); for (key, value) in patch.as_object().unwrap() { rollup[key] = value.clone(); } json!({ "rollup": rollup }) }; let refused = |column: &str, computed: Value, others: Vec| { across(column, computed.clone(), others).expect_err(&format!("{computed} was accepted")).to_string() }; let without = |id: &str| beside().into_iter().filter(|t| t.id != id).collect::>(); let said = refused("customer_name", json!({ "lookup": { "through": "customer", "column": "name" } }), without("person")); assert!(said.contains("not a table here"), "{said}"); let said = refused("customer_name", json!({ "lookup": { "through": "customer", "column": "nickname" } }), beside()); assert!(said.contains("not a declared column"), "{said}"); let said = refused("total", json!({ "lookup": { "through": "customer", "column": "name" } }), beside()); assert!(said.contains("own type"), "{said}"); let said = refused("paid", sum(json!({})), without("payment")); assert!(said.contains("not a table here"), "{said}"); let said = refused("paid", sum(json!({ "link": "note" })), beside()); assert!(said.contains("must be a link"), "{said}"); let said = refused("paid", sum(json!({ "table": "invoice", "link": "customer", "column": "net" })), beside()); assert!(said.contains("a link to one record of this column's table"), "{said}"); let said = refused("paid", sum(json!({ "column": "gone" })), beside()); assert!(said.contains("not a declared column"), "{said}"); let said = refused("paid", sum(json!({ "op": "max", "column": "paid_on" })), beside()); assert!(said.contains("own type"), "{said}"); let said = refused("paid", sum(json!({ "where": { "column": "status", "values": ["bounced"] } })), beside()); assert!(said.contains("choices"), "{said}"); let said = refused("paid", sum(json!({ "where": { "column": "state", "values": ["posted"] } })), beside()); assert!(said.contains("not a declared column"), "{said}"); // first and latest order by the other table's date, or by `by`. let latest = |by: Option<&str>| { let mut rollup = json!({ "table": "invoice_line", "link": "invoice", "op": "latest", "column": "what" }); if let Some(by) = by { rollup["by"] = json!(by); } json!({ "rollup": rollup }) }; let said = refused("label", latest(None), beside()); assert!(said.contains("no date"), "{said}"); let said = refused("label", latest(Some("what")), beside()); assert!(said.contains("a date, a time or a number"), "{said}"); across( "last_paid", json!({ "rollup": { "table": "payment", "link": "invoice", "op": "first", "column": "paid_on" } }), beside(), ) .expect("the other table's own date orders it"); } /// RULE: A computed column may read another computed column but never itself by any path — in one table or round through another — so the core can always order the derivation and it always ends. #[test] fn a_computed_column_never_reads_itself() { let cycle = |result: Result<(), DefinitionError>| { matches!(result, Err(DefinitionError::ComputedCycle { .. })) }; // The filed invoice already chains: label ← customer_name, owed ← total. assert!(cycle(alone("total", json!({ "formula": { "op": "sum", "of": ["total", "tax"] } })))); assert!(cycle(alone("total", json!({ "formula": { "op": "sum", "of": ["owed", "tax"] } })))); assert!(cycle(alone("total", json!({ "formula": { "op": "sum", "of": ["before_tax", "tax"] } })))); // Round through another table: the invoice sums its payments' amounts, // and a payment's amount is looked up from its invoice's paid. let mut others = beside(); others.retain(|table| table.id != "payment"); others.push(table( "payment", Some("paid_on"), json!([ { "key": "note", "type": "text" }, { "key": "invoice", "type": "link", "link_to": "invoice" }, { "key": "amount", "type": "amount", "computed": { "lookup": { "through": "invoice", "column": "paid" } } }, { "key": "status", "type": "choice", "choices": ["pending", "posted"] }, { "key": "paid_on", "type": "date" } ]), )); let filed = invoice()["columns"][11]["computed"].clone(); assert!(cycle(across("paid", filed, others))); } /// RULE: Ordered computed shapes are checked when definitions are saved, so a missing source, wrong type, missing sort or dependency cycle never becomes a stored definition. #[test] fn ordered_shapes_are_validated_at_definition_save() { let mut value = serde_json::to_value(table("movement", None, json!([ {"key":"name", "type":"text"}, {"key":"position", "type":"number"}, {"key":"amount", "type":"amount"} ]))).unwrap(); value["sort"] = json!({"column":"position"}); value["columns"].as_array_mut().unwrap().extend([ json!({"key":"balance", "type":"amount", "computed":{"running":{"column":"amount", "opening":100}}}), json!({"key":"before", "type":"amount", "computed":{"previous":{"column":"balance"}}}) ]); parse(&value).validate().expect("ordered shapes stand at save"); for (path, wrong) in [ ("/columns/3/computed/running/column", json!("missing")), ("/columns/3/computed/running/column", json!("name")), ("/columns/4/computed/previous/column", json!("name")), ("/columns/3/computed/running/column", json!("before")), ("/sort", Value::Null), ("/sort/column", json!("balance")), ("/columns/3/computed/running/opening", json!("100")), ("/columns/3/computed/running/opening", json!(0.5)), ("/columns/3/computed/running/opening", json!(0.0)), ("/columns/3/computed/running/opening", json!(u64::MAX)), ] { let mut invalid = value.clone(); *invalid.pointer_mut(path).unwrap() = wrong; let refused = serde_json::from_value::(invalid) .map(|definition| definition.validate().is_err()).unwrap_or(true); assert!(refused, "save must refuse {path}"); } let mut fractional = value; for index in [2,3,4] { fractional["columns"][index]["type"] = json!("number"); } fractional["columns"][3]["computed"]["running"]["opening"] = json!(0.5); parse(&fractional).validate().expect("generic number openings can have fractions"); } /// RULE: A table-wide opening validates source types and dependency cycles at save, so aggregation cannot bypass the rules on computed columns. #[test] fn running_aggregate_openings_validate_sources_and_cycles() { let mut value = serde_json::to_value(table("movement", None, json!([ {"key":"name", "type":"text"}, {"key":"position", "type":"number"}, {"key":"amount", "type":"amount"} ]))).unwrap(); value["sort"] = json!({"column":"position"}); value["columns"].as_array_mut().unwrap().push(json!({ "key":"balance", "type":"amount", "computed":{"running":{"column":"amount", "opening":{"rollup":{ "table":"opening", "column":"amount", "op":"sum" }}}} })); let movement = parse(&value); movement.validate().unwrap(); let opening = table("opening", None, json!([ {"key":"name", "type":"text"}, {"key":"movement", "type":"link", "link_to":"movement"}, {"key":"amount", "type":"amount"} ])); validate_across(&[&movement, &opening]).unwrap(); assert!(validate_across(&[&movement]).is_err(), "missing source refused"); let mut wrong = opening.clone(); wrong.columns[2].column_type = ColumnType::Number; assert!(validate_across(&[&movement, &wrong]).is_err(), "opening type refused"); let mut cycle = opening.clone(); cycle.columns[2].computed = Some(Computed::Lookup(Lookup { through:"movement".into(), column:"balance".into() })); assert!(validate_across(&[&movement, &cycle]).is_err(), "opening cycle refused"); let decoded = TableDefinition::from_json(&movement.to_json()).unwrap(); assert_eq!(decoded, movement, "the new shape round trips"); } /// RULE: Ordered partitions name real columns at save and participate in dependency checks; an unknown key or self-dependent partition cannot silently combine people's rows. #[test] fn ordered_partitions_validate_columns_and_dependencies() { for shape in ["running", "previous"] { let mut value = serde_json::to_value(table("partitioned", None, json!([ {"key":"name","type":"text"}, {"key":"person","type":"text"}, {"key":"amount","type":"number"}, {"key":"balance","type":"number"} ]))).unwrap(); value["sort"] = json!({"column":"name"}); value["columns"][3]["computed"] = if shape == "running" {json!({"running":{"column":"amount","opening":0}})} else {json!({"previous":{"column":"amount"}})}; value["columns"][3]["computed"][shape]["partition"] = json!(["person"]); parse(&value).validate().unwrap(); value["columns"][3]["computed"][shape]["partition"] = json!(["missing"]); assert!(parse(&value).validate().is_err(),"{shape} must refuse an unknown partition column"); value["columns"][3]["computed"][shape]["partition"] = json!(["balance"]); assert!(parse(&value).validate().is_err(),"{shape} must refuse a cycle through its partition"); } }