Skip to main content

hawdb_core/error/
relational.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::{Display, Formatter};
16
17/// Typed class of a relational refusal, so callers need not parse its text.
18///
19/// The storage crate's relational error reports this as the `source()` of its
20/// constraint and schema variants, which lets
21/// [`HawDBError::from_storage_error`](crate::HawDBError::from_storage_error)
22/// preserve it across the crate boundary.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub enum RelationalErrorKind {
25    /// A row violates a declared constraint, such as a duplicate primary or
26    /// unique key, a NULL in a NOT NULL column, or a missing foreign-key target.
27    Constraint,
28    /// A statement or value does not fit the relational schema, such as a
29    /// value of the wrong type for its column.
30    Schema,
31}
32
33impl RelationalErrorKind {
34    /// Stable lowercase name, as bindings expose it.
35    pub const fn as_str(self) -> &'static str {
36        match self {
37            Self::Constraint => "constraint",
38            Self::Schema => "schema",
39        }
40    }
41}
42
43impl Display for RelationalErrorKind {
44    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
45        formatter.write_str(match self {
46            Self::Constraint => "relational constraint violation",
47            Self::Schema => "relational schema error",
48        })
49    }
50}
51
52impl std::error::Error for RelationalErrorKind {}
53
54/// The layer that reported a relational refusal. It selects the message
55/// prefix, `storage error:` or `execution error:`, and lets bindings keep the
56/// error type that layer has always produced.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58pub enum RelationalErrorSurface {
59    /// Reported through storage, as an autocommit statement's commit does.
60    Storage,
61    /// Reported by a statement inside an explicit transaction.
62    Execution,
63}
64
65impl RelationalErrorSurface {
66    pub(super) const fn prefix(self) -> &'static str {
67        match self {
68            Self::Storage => "storage error",
69            Self::Execution => "execution error",
70        }
71    }
72}
73
74/// Finds a relational refusal kind in `error`'s source chain, including
75/// through the boxed cause of an `io::Error`, which `source` can skip.
76pub fn find_relational_error_kind(
77    error: &(dyn std::error::Error + 'static),
78) -> Option<RelationalErrorKind> {
79    let mut current = Some(error);
80    while let Some(error) = current {
81        if let Some(kind) = error.downcast_ref::<RelationalErrorKind>() {
82            return Some(*kind);
83        }
84        if let Some(kind) = error
85            .downcast_ref::<crate::HawDBError>()
86            .and_then(crate::HawDBError::relational_error_kind)
87        {
88            return Some(kind);
89        }
90        if let Some(error) = error.downcast_ref::<std::io::Error>()
91            && let Some(inner) = error.get_ref()
92            && let Some(kind) = find_relational_error_kind(inner)
93        {
94            return Some(kind);
95        }
96        current = error.source();
97    }
98    None
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::HawDBError;
105
106    /// Stands in for the storage crate's relational error, which core cannot name.
107    #[derive(Debug)]
108    struct Refusal(RelationalErrorKind, &'static str);
109
110    impl Display for Refusal {
111        fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
112            write!(formatter, "{}: {}", self.0, self.1)
113        }
114    }
115
116    impl std::error::Error for Refusal {
117        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
118            Some(match self.0 {
119                RelationalErrorKind::Constraint => &RelationalErrorKind::Constraint,
120                RelationalErrorKind::Schema => &RelationalErrorKind::Schema,
121            })
122        }
123    }
124
125    #[test]
126    fn storage_conversion_keeps_the_kind_and_the_storage_text() {
127        for (kind, detail) in [
128            (RelationalErrorKind::Constraint, "duplicate primary key 1"),
129            (RelationalErrorKind::Schema, "column id expects Int64"),
130        ] {
131            let text = format!("storage error: {kind}: {detail}");
132            let direct = HawDBError::from_storage_error(Refusal(kind, detail));
133            assert_eq!(direct.relational_error_kind(), Some(kind));
134            assert_eq!(direct.to_string(), text);
135            // Through an io::Error wrapper, and once more after conversion.
136            let wrapped =
137                HawDBError::from_storage_error(std::io::Error::other(Refusal(kind, detail)));
138            assert_eq!(wrapped, direct);
139            assert_eq!(HawDBError::from_storage_error(direct.clone()), direct);
140            let context = HawDBError::from_storage_error_with_context(Refusal(kind, detail), "ctx");
141            assert_eq!(context.relational_error_kind(), Some(kind));
142            assert_eq!(
143                context.to_string(),
144                format!("storage error: ctx: {kind}: {detail}")
145            );
146        }
147    }
148
149    #[test]
150    fn execution_surface_keeps_the_execution_text() {
151        let error = HawDBError::relational(
152            RelationalErrorKind::Constraint,
153            RelationalErrorSurface::Execution,
154            "relational constraint violation: duplicate",
155        );
156        assert_eq!(
157            error.to_string(),
158            "execution error: relational constraint violation: duplicate"
159        );
160        assert_eq!(
161            error.relational_error_kind(),
162            Some(RelationalErrorKind::Constraint)
163        );
164        assert_eq!(
165            error.relational_error_surface(),
166            Some(RelationalErrorSurface::Execution)
167        );
168    }
169
170    #[test]
171    fn other_storage_errors_have_no_relational_kind() {
172        let error = HawDBError::from_storage_error(std::io::Error::other("disk"));
173        assert!(matches!(error, HawDBError::Storage(_)));
174        assert_eq!(error.relational_error_kind(), None);
175        assert_eq!(
176            HawDBError::Execution("x".into()).relational_error_kind(),
177            None
178        );
179    }
180}