use serde::{Deserialize, Serialize};
pub const INVALID_QUERY: &str = "invalid_query";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct Violation {
pub path: String,
pub code: String,
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
pub params: serde_json::Map<String, serde_json::Value>,
pub message: String,
}
impl Violation {
pub fn new(path: impl Into<String>, code: impl Into<String>, message: impl Into<String>) -> Self {
Self { path: path.into(), code: code.into(), params: serde_json::Map::new(), message: message.into() }
}
pub fn invalid_query(parameter: &str, reason: &str, message: impl Into<String>) -> Self {
Self::new(parameter, INVALID_QUERY, message)
.with_param("parameter", parameter)
.with_param("reason", reason)
}
pub fn with_param(mut self, name: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
self.params.insert(name.into(), value.into());
self
}
}
pub fn batch_item_path(index: usize, path: &str) -> String {
if path.is_empty() {
index.to_string()
} else {
format!("{index}/{path}")
}
}
pub fn code_from_constraint(constraint: &str) -> String {
for prefix in ["ck_", "uq_", "ex_", "tg_"] {
if let Some(rest) = constraint.strip_prefix(prefix) {
if let Some((_, code)) = rest.split_once("__") {
if !code.is_empty() {
return code.to_string();
}
}
}
}
constraint.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_generated_constraint_name_carries_its_rule_code() {
assert_eq!(code_from_constraint("ck_journals__unbalanced"), "unbalanced");
assert_eq!(code_from_constraint("uq_accounts__account_code_taken"), "account_code_taken");
assert_eq!(code_from_constraint("ex_tax_rates__overlapping_validity"), "overlapping_validity");
assert_eq!(code_from_constraint("fiscal_period_status_transition"), "fiscal_period_status_transition");
assert_eq!(code_from_constraint("ck_legacy"), "ck_legacy");
}
#[test]
fn a_refused_query_parameter_names_itself_and_its_reason() {
let v = Violation::invalid_query("sort_by", "unknown_column", "`sort_by`: `x` is not a field");
assert_eq!(
serde_json::to_value(&v).unwrap(),
serde_json::json!({
"path": "sort_by",
"code": "invalid_query",
"params": { "parameter": "sort_by", "reason": "unknown_column" },
"message": "`sort_by`: `x` is not a field"
})
);
}
#[test]
fn a_violation_serializes_without_empty_params() {
let v = Violation::new("status", "field_not_writable", "`status` changes only through its verbs");
assert_eq!(
serde_json::to_value(&v).unwrap(),
serde_json::json!({ "path": "status", "code": "field_not_writable", "message": "`status` changes only through its verbs" })
);
let v = Violation::new("name", "max_length", "too long").with_param("max", 255);
assert_eq!(serde_json::to_value(&v).unwrap()["params"], serde_json::json!({ "max": 255 }));
}
}