Skip to main content

icydb_core/traits/
mod.rs

1#[macro_use]
2mod macros;
3mod view;
4mod visitor;
5
6pub use view::*;
7pub use visitor::*;
8
9// -----------------------------------------------------------------------------
10// Standard re-exports for `traits::X` ergonomics
11// -----------------------------------------------------------------------------
12
13pub use canic_cdk::structures::storable::Storable;
14pub use num_traits::{FromPrimitive as NumFromPrimitive, NumCast, ToPrimitive as NumToPrimitive};
15pub use serde::{Deserialize, Serialize, de::DeserializeOwned};
16pub use std::{
17    cmp::{Eq, Ordering, PartialEq},
18    convert::From,
19    default::Default,
20    fmt::Debug,
21    hash::Hash,
22    ops::{Add, AddAssign, Deref, DerefMut, Div, DivAssign, Mul, MulAssign, Rem, Sub, SubAssign},
23};
24
25use crate::{prelude::*, value::ValueEnum, visitor::VisitorContext};
26
27// ============================================================================
28// FOUNDATIONAL KINDS
29// ============================================================================
30//
31// These traits define *where* something lives in the system,
32// not what data it contains.
33//
34
35/// Fully-qualified schema path.
36pub trait Path {
37    const PATH: &'static str;
38}
39
40/// Marker for all schema/runtime nodes.
41pub trait Kind: Path + 'static {}
42impl<T> Kind for T where T: Path + 'static {}
43
44/// Marker for canister namespaces.
45pub trait CanisterKind: Kind {}
46
47/// Marker for data stores bound to a canister.
48pub trait DataStoreKind: Kind {
49    type Canister: CanisterKind;
50}
51
52/// Marker for index stores bound to a canister.
53pub trait IndexStoreKind: Kind {
54    type Canister: CanisterKind;
55}
56
57// ============================================================================
58// ENTITY IDENTITY & SCHEMA
59// ============================================================================
60//
61// These traits describe *what an entity is*, not how it is stored
62// or manipulated at runtime.
63//
64
65/// Marker trait for entity identity types.
66///
67/// Identity types:
68/// - Are cheap to copy
69/// - Are totally ordered
70/// - Can be converted to/from query Values
71///
72/// They are NOT required to be persistable.
73pub trait EntityKey: Copy + Debug + Eq + Ord + FieldValue + 'static {}
74impl<T> EntityKey for T where T: Copy + Debug + Eq + Ord + FieldValue + 'static {}
75
76///
77/// EntityIdentity
78/// Identity-only facts about an entity.
79///
80
81pub trait EntityIdentity {
82    type Id: EntityKey;
83
84    const ENTITY_NAME: &'static str;
85    const PRIMARY_KEY: &'static str;
86}
87
88///
89/// EntitySchema
90/// Declared schema facts for an entity.
91///
92
93pub trait EntitySchema: EntityIdentity {
94    const MODEL: &'static EntityModel;
95    const FIELDS: &'static [&'static str];
96    const INDEXES: &'static [&'static IndexModel];
97}
98
99// ============================================================================
100// ENTITY RUNTIME COMPOSITION
101// ============================================================================
102//
103// These traits bind schema-defined entities into runtime placement.
104//
105
106/// Runtime placement of an entity.
107pub trait EntityPlacement {
108    type DataStore: DataStoreKind;
109    type Canister: CanisterKind;
110}
111
112/// Fully runtime-bound entity.
113///
114/// This is the *maximum* entity contract and should only be
115/// required by code that actually touches storage or execution.
116pub trait EntityKind: EntitySchema + EntityPlacement + Kind + TypeKind {}
117
118// ============================================================================
119// ENTITY VALUES
120// ============================================================================
121//
122// These traits describe *instances* of entities.
123//
124
125/// A concrete entity value.
126///
127/// This trait is intentionally lighter than `EntityKind`.
128/// It does NOT imply storage placement.
129pub trait EntityValue: EntityIdentity + FieldValues {
130    fn id(&self) -> Self::Id;
131    fn set_id(&mut self, id: Self::Id);
132}
133
134/// Marker for entities with exactly one logical row.
135pub trait SingletonEntity: EntityValue {}
136
137// ============================================================================
138// TYPE SYSTEM CONTRACTS
139// ============================================================================
140//
141// These traits define behavioral expectations for schema-defined types.
142//
143
144/// Any schema-defined data type.
145///
146/// This is a *strong* contract and should only be required
147/// where full lifecycle semantics are needed.
148pub trait TypeKind:
149    Kind
150    + View
151    + Clone
152    + Default
153    + Serialize
154    + DeserializeOwned
155    + Sanitize
156    + Validate
157    + Visitable
158    + PartialEq
159{
160}
161
162impl<T> TypeKind for T where
163    T: Kind
164        + View
165        + Clone
166        + Default
167        + DeserializeOwned
168        + PartialEq
169        + Serialize
170        + Sanitize
171        + Validate
172        + Visitable
173{
174}
175
176/// ============================================================================
177/// QUERY VALUE BOUNDARIES
178/// ============================================================================
179
180/// Explicit iteration contract for list/set wrapper types.
181/// Avoids implicit deref-based access to inner collections.
182pub trait Collection {
183    type Item;
184
185    /// Returns an iterator over the collection's items.
186    fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = &'a Self::Item> + 'a>;
187
188    /// Returns the number of items in the collection.
189    fn len(&self) -> usize;
190
191    /// Returns true if the collection contains no items.
192    fn is_empty(&self) -> bool {
193        self.len() == 0
194    }
195}
196
197/// Explicit iteration contract for map wrapper types.
198/// Avoids implicit deref-based access to inner collections.
199pub trait MapCollection {
200    type Key;
201    type Value;
202
203    /// Returns an iterator over the map's key/value pairs.
204    fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (&'a Self::Key, &'a Self::Value)> + 'a>;
205
206    /// Returns the number of entries in the map.
207    fn len(&self) -> usize;
208
209    /// Returns true if the map contains no entries.
210    fn is_empty(&self) -> bool {
211        self.len() == 0
212    }
213}
214
215pub trait EnumValue {
216    fn to_value_enum(&self) -> ValueEnum;
217}
218
219pub trait FieldValues {
220    fn get_value(&self, field: &str) -> Option<Value>;
221}
222
223///
224/// FieldValue
225///
226/// Conversion boundary for values used in query predicates.
227///
228/// Represents values that can appear on the *right-hand side* of predicates.
229///
230
231pub trait FieldValue {
232    fn to_value(&self) -> Value {
233        Value::Unsupported
234    }
235
236    #[must_use]
237    fn from_value(_value: &Value) -> Option<Self>
238    where
239        Self: Sized,
240    {
241        None
242    }
243}
244
245impl FieldValue for &str {
246    fn to_value(&self) -> Value {
247        Value::Text((*self).to_string())
248    }
249}
250
251impl FieldValue for String {
252    fn to_value(&self) -> Value {
253        Value::Text(self.clone())
254    }
255}
256
257impl<T: FieldValue> FieldValue for Option<T> {
258    fn to_value(&self) -> Value {
259        match self {
260            Some(v) => v.to_value(),
261            None => Value::None,
262        }
263    }
264}
265
266impl<T: FieldValue> FieldValue for Box<T> {
267    fn to_value(&self) -> Value {
268        (**self).to_value()
269    }
270}
271
272impl<T: FieldValue> FieldValue for Vec<Box<T>> {
273    fn to_value(&self) -> Value {
274        Value::List(self.iter().map(FieldValue::to_value).collect())
275    }
276}
277
278// impl_field_value
279#[macro_export]
280macro_rules! impl_field_value {
281    ( $( $type:ty => $variant:ident ),* $(,)? ) => {
282        $(
283            impl FieldValue for $type {
284                fn to_value(&self) -> Value {
285                    Value::$variant((*self).into())
286                }
287
288                fn from_value(value: &Value) -> Option<Self> {
289                    match value {
290                        Value::$variant(v) => (*v).try_into().ok(),
291                        _ => None,
292                    }
293                }
294            }
295        )*
296    };
297}
298
299impl_field_value!(
300    i8 => Int,
301    i16 => Int,
302    i32 => Int,
303    i64 => Int,
304    u8 => Uint,
305    u16 => Uint,
306    u32 => Uint,
307    u64 => Uint,
308    bool => Bool,
309);
310
311/// ============================================================================
312/// MISC HELPERS
313/// ============================================================================
314
315///
316/// Inner
317///
318/// For newtypes to expose their innermost value.
319///
320pub trait Inner<T> {
321    fn inner(&self) -> &T;
322    fn into_inner(self) -> T;
323}
324
325// impl_inner
326#[macro_export]
327macro_rules! impl_inner {
328    ($($type:ty),*) => {
329        $(
330            impl Inner<$type> for $type {
331                fn inner(&self) -> &$type {
332                    &self
333                }
334                fn into_inner(self) -> $type {
335                    self
336                }
337            }
338        )*
339    };
340}
341
342impl_inner!(
343    bool, f32, f64, i8, i16, i32, i64, i128, String, u8, u16, u32, u64, u128
344);
345
346/// ============================================================================
347/// SANITIZATION / VALIDATION
348/// ============================================================================
349
350///
351/// Sanitizer
352///
353/// Transforms a value into a sanitized version.
354///
355pub trait Sanitizer<T> {
356    fn sanitize(&self, value: &mut T) -> Result<(), String>;
357}
358
359///
360/// Validator
361///
362/// Allows a node to validate values.
363///
364pub trait Validator<T: ?Sized> {
365    fn validate(&self, value: &T, ctx: &mut dyn VisitorContext);
366}