Skip to main content

icydb_model/node/
constraint.rs

1//! Accepted-check declarations retained by the host authoring graph.
2
3use crate::prelude::*;
4use icydb_schema::{SchemaContractError, SourceCheckExpr};
5
6use crate::node::Schema;
7
8/// Compiler-produced source-expression projection for one accepted check.
9pub type SourceExpressionResolver = fn(&Schema) -> Result<SourceCheckExpr, SchemaContractError>;
10
11///
12/// CheckConstraint
13///
14/// Source-keyed accepted-check declaration. The SQL spelling remains authored
15/// input until the compiler projection lowers it into the public source AST.
16///
17
18#[derive(Clone, Debug, Serialize)]
19pub struct CheckConstraint {
20    source_key: &'static str,
21    name: &'static str,
22    check: &'static str,
23    #[serde(skip)]
24    expression: SourceExpressionResolver,
25}
26
27impl CheckConstraint {
28    /// Construct one source-keyed accepted-check declaration.
29    #[must_use]
30    pub const fn new(
31        source_key: &'static str,
32        name: &'static str,
33        check: &'static str,
34        expression: SourceExpressionResolver,
35    ) -> Self {
36        Self {
37            source_key,
38            name,
39            check,
40            expression,
41        }
42    }
43
44    /// Borrow the immutable constraint source key.
45    #[must_use]
46    pub const fn source_key(&self) -> &'static str {
47        self.source_key
48    }
49
50    /// Borrow the editable accepted-check name.
51    #[must_use]
52    pub const fn name(&self) -> &'static str {
53        self.name
54    }
55
56    /// Borrow the authored check expression.
57    #[must_use]
58    pub const fn check(&self) -> &'static str {
59        self.check
60    }
61
62    /// Lower the compiler-validated expression into the public source AST.
63    ///
64    /// # Errors
65    ///
66    /// Returns a typed proposal error when an enum literal no longer resolves
67    /// through the sealed graph or the expression violates public bounds.
68    pub fn source_expression(
69        &self,
70        schema: &Schema,
71    ) -> Result<SourceCheckExpr, SchemaContractError> {
72        (self.expression)(schema)
73    }
74}
75
76impl ValidateNode for CheckConstraint {
77    fn validate(&self) -> Result<(), ErrorTree> {
78        let mut errs = ErrorTree::new();
79        validate_source_key(
80            &mut errs,
81            "constraint",
82            self.source_key(),
83            icydb_schema::ConstraintSourceKey::try_new,
84        );
85        errs.result()
86    }
87}
88
89impl VisitableNode for CheckConstraint {
90    fn route_key(&self) -> String {
91        self.name().to_string()
92    }
93}