backbone_core/
violation.rs1use serde::{Deserialize, Serialize};
18
19#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
22pub struct Violation {
23 pub path: String,
26 pub code: String,
28 #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
30 pub params: serde_json::Map<String, serde_json::Value>,
31 pub message: String,
33}
34
35impl Violation {
36 pub fn new(path: impl Into<String>, code: impl Into<String>, message: impl Into<String>) -> Self {
37 Self { path: path.into(), code: code.into(), params: serde_json::Map::new(), message: message.into() }
38 }
39
40 pub fn with_param(mut self, name: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
42 self.params.insert(name.into(), value.into());
43 self
44 }
45}
46
47pub fn code_from_constraint(constraint: &str) -> String {
56 for prefix in ["ck_", "uq_", "ex_", "tg_"] {
57 if let Some(rest) = constraint.strip_prefix(prefix) {
58 if let Some((_, code)) = rest.split_once("__") {
59 if !code.is_empty() {
60 return code.to_string();
61 }
62 }
63 }
64 }
65 constraint.to_string()
66}
67
68#[cfg(test)]
69mod tests {
70 use super::*;
71
72 #[test]
73 fn a_generated_constraint_name_carries_its_rule_code() {
74 assert_eq!(code_from_constraint("ck_journals__unbalanced"), "unbalanced");
75 assert_eq!(code_from_constraint("uq_accounts__account_code_taken"), "account_code_taken");
76 assert_eq!(code_from_constraint("ex_tax_rates__overlapping_validity"), "overlapping_validity");
77 assert_eq!(code_from_constraint("fiscal_period_status_transition"), "fiscal_period_status_transition");
79 assert_eq!(code_from_constraint("ck_legacy"), "ck_legacy");
81 }
82
83 #[test]
84 fn a_violation_serializes_without_empty_params() {
85 let v = Violation::new("status", "field_not_writable", "`status` changes only through its verbs");
86 assert_eq!(
87 serde_json::to_value(&v).unwrap(),
88 serde_json::json!({ "path": "status", "code": "field_not_writable", "message": "`status` changes only through its verbs" })
89 );
90 let v = Violation::new("name", "max_length", "too long").with_param("max", 255);
91 assert_eq!(serde_json::to_value(&v).unwrap()["params"], serde_json::json!({ "max": 255 }));
92 }
93}