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::*, types::Id, 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///
36/// Path
37/// Fully-qualified schema path.
38///
39
40pub trait Path {
41 const PATH: &'static str;
42}
43
44/// Marker for all schema/runtime nodes.
45pub trait Kind: Path + 'static {}
46impl<T> Kind for T where T: Path + 'static {}
47
48/// Marker for canister namespaces.
49pub trait CanisterKind: Kind {}
50
51/// Marker for data stores bound to a canister.
52pub trait DataStoreKind: Kind {
53 type Canister: CanisterKind;
54}
55
56/// Marker for index stores bound to a canister.
57pub trait IndexStoreKind: Kind {
58 type Canister: CanisterKind;
59}
60
61// ============================================================================
62// ENTITY IDENTITY & SCHEMA
63// ============================================================================
64//
65// These traits describe *what an entity is*, not how it is stored
66// or manipulated at runtime.
67//
68
69///
70/// EntityKey
71///
72/// Marker trait for raw entity key material used at storage boundaries.
73///
74
75pub trait EntityKey: Copy + Debug + Eq + Ord + FieldValue + 'static {}
76impl<T> EntityKey for T where T: Copy + Debug + Eq + Ord + FieldValue + 'static {}
77
78///
79/// EntityStorageKey
80///
81/// Raw storage-key facts about an entity.
82///
83
84pub trait EntityStorageKey {
85 type Key: EntityKey;
86}
87
88///
89/// EntityIdentity
90///
91/// Semantic identity facts about an entity.
92/// `IDENTITY_NAMESPACE` is the stable namespace used for one-way
93/// external identity projection and SHOULD remain unchanged across
94/// schema/type renames when external identity continuity is required.
95///
96
97pub trait EntityIdentity: EntityStorageKey {
98 const ENTITY_NAME: &'static str;
99 const PRIMARY_KEY: &'static str;
100 const IDENTITY_NAMESPACE: &'static str;
101}
102
103///
104/// EntitySchema
105///
106/// Declared schema facts for an entity.
107///
108
109pub trait EntitySchema: EntityIdentity {
110 const MODEL: &'static EntityModel;
111 const FIELDS: &'static [&'static str];
112 const INDEXES: &'static [&'static IndexModel];
113}
114
115// ============================================================================
116// ENTITY RUNTIME COMPOSITION
117// ============================================================================
118//
119// These traits bind schema-defined entities into runtime placement.
120//
121
122///
123/// EntityPlacement
124///
125/// Runtime placement of an entity
126///
127
128pub trait EntityPlacement {
129 type DataStore: DataStoreKind;
130 type Canister: CanisterKind;
131}
132
133///
134/// EntityKind
135///
136/// Fully runtime-bound entity.
137///
138/// This is the *maximum* entity contract and should only be
139/// required by code that actually touches storage or execution.
140///
141
142pub trait EntityKind: EntitySchema + EntityPlacement + Kind + TypeKind {}
143
144// ============================================================================
145// ENTITY VALUES
146// ============================================================================
147//
148// These traits describe *instances* of entities.
149//
150
151///
152/// EntityValue
153///
154/// A concrete entity value.
155///
156/// This trait is intentionally lighter than `EntityKind`.
157/// It does NOT imply storage placement.
158///
159
160pub trait EntityValue: EntityIdentity + FieldValues + Sized {
161 fn id(&self) -> Id<Self>;
162}
163
164/// Marker for entities with exactly one logical row.
165pub trait SingletonEntity: EntityValue {}
166
167///
168// ============================================================================
169// TYPE SYSTEM CONTRACTS
170// ============================================================================
171//
172// These traits define behavioral expectations for schema-defined types.
173//
174
175///
176/// TypeKind
177///
178/// Any schema-defined data type.
179///
180/// This is a *strong* contract and should only be required
181/// where full lifecycle semantics are needed.
182///
183
184pub trait TypeKind:
185 Kind
186 + View
187 + Clone
188 + Default
189 + Serialize
190 + DeserializeOwned
191 + Sanitize
192 + Validate
193 + Visitable
194 + PartialEq
195{
196}
197
198impl<T> TypeKind for T where
199 T: Kind
200 + View
201 + Clone
202 + Default
203 + DeserializeOwned
204 + PartialEq
205 + Serialize
206 + Sanitize
207 + Validate
208 + Visitable
209{
210}
211
212/// ============================================================================
213/// QUERY VALUE BOUNDARIES
214/// ============================================================================
215
216///
217/// Collection
218///
219/// Explicit iteration contract for list/set wrapper types.
220/// Avoids implicit deref-based access to inner collections.
221///
222
223pub trait Collection {
224 type Item;
225
226 /// Iterator over the collection's items, tied to the borrow of `self`.
227 type Iter<'a>: Iterator<Item = &'a Self::Item> + 'a
228 where
229 Self: 'a;
230
231 /// Returns an iterator over the collection's items.
232 fn iter(&self) -> Self::Iter<'_>;
233
234 /// Returns the number of items in the collection.
235 fn len(&self) -> usize;
236
237 /// Returns true if the collection contains no items.
238 fn is_empty(&self) -> bool {
239 self.len() == 0
240 }
241}
242
243///
244/// MapCollection
245///
246/// Explicit iteration contract for map wrapper types.
247/// Avoids implicit deref-based access to inner collections.
248///
249
250pub trait MapCollection {
251 type Key;
252 type Value;
253
254 /// Iterator over the map's key/value pairs, tied to the borrow of `self`.
255 type Iter<'a>: Iterator<Item = (&'a Self::Key, &'a Self::Value)> + 'a
256 where
257 Self: 'a;
258
259 /// Returns an iterator over the map's key/value pairs.
260 fn iter(&self) -> Self::Iter<'_>;
261
262 /// Returns the number of entries in the map.
263 fn len(&self) -> usize;
264
265 /// Returns true if the map contains no entries.
266 fn is_empty(&self) -> bool {
267 self.len() == 0
268 }
269}
270
271pub trait EnumValue {
272 fn to_value_enum(&self) -> ValueEnum;
273}
274
275pub trait FieldValues {
276 fn get_value(&self, field: &str) -> Option<Value>;
277}
278
279///
280/// FieldValue
281///
282/// Conversion boundary for values used in query predicates.
283///
284/// Represents values that can appear on the *right-hand side* of predicates.
285///
286
287pub trait FieldValue {
288 fn to_value(&self) -> Value {
289 Value::Unsupported
290 }
291
292 #[must_use]
293 fn from_value(_value: &Value) -> Option<Self>
294 where
295 Self: Sized,
296 {
297 None
298 }
299}
300
301impl FieldValue for &str {
302 fn to_value(&self) -> Value {
303 Value::Text((*self).to_string())
304 }
305}
306
307impl FieldValue for String {
308 fn to_value(&self) -> Value {
309 Value::Text(self.clone())
310 }
311}
312
313impl<T: FieldValue> FieldValue for Option<T> {
314 fn to_value(&self) -> Value {
315 match self {
316 Some(v) => v.to_value(),
317 None => Value::None,
318 }
319 }
320}
321
322impl<T: FieldValue> FieldValue for Box<T> {
323 fn to_value(&self) -> Value {
324 (**self).to_value()
325 }
326}
327
328impl<T: FieldValue> FieldValue for Vec<Box<T>> {
329 fn to_value(&self) -> Value {
330 Value::List(self.iter().map(FieldValue::to_value).collect())
331 }
332}
333
334// impl_field_value
335#[macro_export]
336macro_rules! impl_field_value {
337 ( $( $type:ty => $variant:ident ),* $(,)? ) => {
338 $(
339 impl FieldValue for $type {
340 fn to_value(&self) -> Value {
341 Value::$variant((*self).into())
342 }
343
344 fn from_value(value: &Value) -> Option<Self> {
345 match value {
346 Value::$variant(v) => (*v).try_into().ok(),
347 _ => None,
348 }
349 }
350 }
351 )*
352 };
353}
354
355impl_field_value!(
356 i8 => Int,
357 i16 => Int,
358 i32 => Int,
359 i64 => Int,
360 u8 => Uint,
361 u16 => Uint,
362 u32 => Uint,
363 u64 => Uint,
364 bool => Bool,
365);
366
367/// ============================================================================
368/// MISC HELPERS
369/// ============================================================================
370
371///
372/// Inner
373///
374/// For newtypes to expose their innermost value.
375///
376pub trait Inner<T> {
377 fn inner(&self) -> &T;
378 fn into_inner(self) -> T;
379}
380
381// impl_inner
382#[macro_export]
383macro_rules! impl_inner {
384 ($($type:ty),*) => {
385 $(
386 impl Inner<$type> for $type {
387 fn inner(&self) -> &$type {
388 &self
389 }
390 fn into_inner(self) -> $type {
391 self
392 }
393 }
394 )*
395 };
396}
397
398impl_inner!(
399 bool, f32, f64, i8, i16, i32, i64, i128, String, u8, u16, u32, u64, u128
400);
401
402/// ============================================================================
403/// SANITIZATION / VALIDATION
404/// ============================================================================
405
406///
407/// Sanitizer
408///
409/// Transforms a value into a sanitized version.
410///
411pub trait Sanitizer<T> {
412 fn sanitize(&self, value: &mut T) -> Result<(), String>;
413}
414
415///
416/// Validator
417///
418/// Allows a node to validate values.
419///
420pub trait Validator<T: ?Sized> {
421 fn validate(&self, value: &T, ctx: &mut dyn VisitorContext);
422}