Skip to main content

ic_db/defaults/
mod.rs

1//! Literal insert policy metadata, encoded through the owned scalar codec.
2
3use crate::{Error, FieldType, codec::Encoder};
4
5#[cfg(test)]
6mod tests;
7
8/// A compiled literal used only when an insert input omits its field.
9/// These are schema constants, not a dynamic query or mutation value model.
10#[derive(Debug, PartialEq, Eq)]
11pub enum LiteralDefault {
12    /// Exact unsigned integer literal; must fit the declared unsigned width.
13    Nat(u128),
14    /// Exact signed integer literal; must fit the declared signed width.
15    Int(i128),
16    /// Boolean literal.
17    Bool(bool),
18    /// UTF-8 text within the declared byte limit.
19    Text(&'static str),
20    /// Raw bytes within the declared Blob byte limit.
21    Blob(&'static [u8]),
22}
23
24impl LiteralDefault {
25    pub(crate) fn encode(&self, value: FieldType) -> Result<Vec<u8>, Error> {
26        let mut writer = Encoder::new();
27        let invalid = |_| Error::InvalidSchema;
28        match (self, value) {
29            (Self::Nat(n), FieldType::Nat8) => writer.nat8((*n).try_into().map_err(invalid)?)?,
30            (Self::Nat(n), FieldType::Nat16) => writer.nat16((*n).try_into().map_err(invalid)?)?,
31            (Self::Nat(n), FieldType::Nat32) => writer.nat32((*n).try_into().map_err(invalid)?)?,
32            (Self::Nat(n), FieldType::Nat64) => writer.nat64((*n).try_into().map_err(invalid)?)?,
33            (Self::Nat(n), FieldType::Nat128) => writer.nat128(*n)?,
34            (Self::Int(n), FieldType::Int8) => writer.int8((*n).try_into().map_err(invalid)?)?,
35            (Self::Int(n), FieldType::Int16) => writer.int16((*n).try_into().map_err(invalid)?)?,
36            (Self::Int(n), FieldType::Int32) => writer.int32((*n).try_into().map_err(invalid)?)?,
37            (Self::Int(n), FieldType::Int64) => writer.int64((*n).try_into().map_err(invalid)?)?,
38            (Self::Int(n), FieldType::Int128) => writer.int128(*n)?,
39            (Self::Bool(b), FieldType::Bool) => writer.boolean(*b)?,
40            (Self::Text(s), FieldType::Text { max_bytes }) if s.len() <= max_bytes as usize => {
41                writer
42                    .bytes(s.as_bytes())
43                    .map_err(|_| Error::InvalidSchema)?;
44            }
45            (Self::Blob(bytes), FieldType::Blob { max_bytes })
46                if bytes.len() <= max_bytes as usize =>
47            {
48                writer.bytes(bytes).map_err(|_| Error::InvalidSchema)?;
49            }
50            _ => return Err(Error::InvalidSchema),
51        }
52        Ok(writer.finish())
53    }
54}
55
56/// Typed insert construction with omission distinct from explicit optional absence.
57/// Generated inputs implement this once per entity; execution stays in `Batch`.
58/// Managed fields have no input setters:
59/// ```compile_fail
60/// use ic_db::entity;
61/// #[entity(pk(field="id"), fields(
62///     field(name="id",value(item(prim="Nat64"))),
63///     field(name="created",value(item(prim="Timestamp")),managed="created_at")
64/// ))]
65/// struct Entry {}
66/// let input = Entry::insert().id(1).created(ic_db::Timestamp::from_millis(0));
67/// ```
68pub trait InsertInput: Sized {
69    /// The fully materialized entity admitted through the ordinary write path.
70    type Entity: crate::Entity;
71    /// Resolve omitted fields without reading or mutating persistent state.
72    /// # Errors
73    /// Refuses a missing required field or managed time without a batch context.
74    /// Field/row bounds are checked by batch insertion.
75    fn into_entity(self) -> Result<Self::Entity, Error> {
76        self.__into_entity(None)
77    }
78    /// Materialize generated input using the batch's captured time.
79    #[doc(hidden)]
80    fn __into_entity(self, time: Option<crate::Timestamp>) -> Result<Self::Entity, Error>;
81}