vlorql_core/errors/
validation.rs1use serde::{Deserialize, Serialize};
4
5use super::vlorql_error::VlorQLError;
6
7#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct ValidationErrors(pub Vec<VlorQLError>);
30
31impl std::fmt::Display for ValidationErrors {
32 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33 match self.0.len() {
34 0 => formatter.write_str("no validation errors"),
35 1 => {
36 let error = &self.0[0];
37 write!(
38 formatter,
39 "{} validation error: {}",
40 error.error_code(),
41 error
42 )
43 }
44 count => {
45 writeln!(
46 formatter,
47 "{count} validation errors occurred (codes: {}):",
48 self.0
49 .iter()
50 .map(VlorQLError::error_code)
51 .collect::<Vec<_>>()
52 .join(", ")
53 )?;
54 for (index, error) in self.0.iter().enumerate() {
55 writeln!(formatter, " [{index}] {}: {error}", error.error_code())?;
56 }
57 Ok(())
58 }
59 }
60 }
61}
62
63impl std::error::Error for ValidationErrors {
64 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
65 None
66 }
67}
68
69impl ValidationErrors {
70 pub fn new<I>(errors: I) -> Self
72 where
73 I: IntoIterator<Item = VlorQLError>,
74 {
75 Self(errors.into_iter().collect())
76 }
77
78 pub fn validate<I>(errors: I) -> Result<(), Self>
80 where
81 I: IntoIterator<Item = VlorQLError>,
82 {
83 let errors = Self::new(errors);
84 if errors.0.is_empty() {
85 Ok(())
86 } else {
87 Err(errors)
88 }
89 }
90
91 pub fn len(&self) -> usize {
93 self.0.len()
94 }
95
96 pub fn is_empty(&self) -> bool {
98 self.0.is_empty()
99 }
100
101 pub fn as_slice(&self) -> &[VlorQLError] {
103 &self.0
104 }
105
106 pub fn into_inner(self) -> Vec<VlorQLError> {
108 self.0
109 }
110}
111
112impl From<Vec<VlorQLError>> for ValidationErrors {
113 fn from(errors: Vec<VlorQLError>) -> Self {
114 Self(errors)
115 }
116}
117
118pub fn validate<I>(errors: I) -> Result<(), ValidationErrors>
120where
121 I: IntoIterator<Item = VlorQLError>,
122{
123 ValidationErrors::validate(errors)
124}