Skip to main content

backbone_core/
violation.rs

1//! The shape of a refused write: one [`Violation`] per broken rule, each with
2//! the field it concerns, a stable code, the values the rule was checked
3//! against, and a sentence a person can act on.
4//!
5//! ```json
6//! { "success": false,
7//!   "error": "validation failed: field_not_writable: `status` …",
8//!   "violations": [
9//!     { "path": "status", "code": "field_not_writable", "params": {}, "message": "…" } ] }
10//! ```
11//!
12//! The `error` string stays, so a client that reads only it keeps working; a
13//! form reads `violations` to mark each field by its code. A violation the
14//! database raises carries the same code as the application-side check, read
15//! from the constraint's name (see [`code_from_constraint`]).
16
17use serde::{Deserialize, Serialize};
18
19/// One broken rule.
20#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
22pub struct Violation {
23    /// The field it concerns, in the casing the entity serializes, with list
24    /// indices for child rows (`lines/3/amount`); empty for a whole-record rule.
25    pub path: String,
26    /// A stable snake_case code, the same on every layer that enforces it.
27    pub code: String,
28    /// The values the rule was checked against (`{ "max": 255 }`).
29    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
30    pub params: serde_json::Map<String, serde_json::Value>,
31    /// What went wrong, said so a person can fix it.
32    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    /// Add one checked-against value.
41    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
47/// The rule code a database constraint stands for.
48///
49/// Generated constraints are named `ck_<table>__<code>` (CHECK),
50/// `uq_<table>__<code>` (unique index), `ex_<table>__<code>` (exclusion) and
51/// `tg_<table>__<code>` (constraint trigger), so a violation the database
52/// raises maps back to the code of the rule it enforces. A constraint named
53/// otherwise is its own code: hand-written triggers raise with a constraint
54/// name chosen to be read (`fiscal_period_status_transition`).
55pub 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        // A constraint named for reading is its own code.
78        assert_eq!(code_from_constraint("fiscal_period_status_transition"), "fiscal_period_status_transition");
79        // A prefix without the separator is not a generated name.
80        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}