Skip to main content

ic_db/
lib.rs

1#![forbid(unsafe_code)]
2//! Experimental IC database: compiled schemas and synchronous bounded records.
3//! Schema modules can import the declaration attributes and value types from
4//! [`design::prelude`].
5//!
6//! This M1 slice supports 8/16/32/64/128-bit integers, U256, Ulid, Date, Timestamp, Duration, Decimal,
7//! finite Float32/Float64, Bool, Principal, Account/Subaccount and bounded Text/Blob, with optional
8//! values. Named records and unit/payload enums support bounded recursion via explicit
9//! indirection and ordered lists; traversals share byte, depth, structured-value
10//! and total collection-item limits. Sets/maps use strict scalar/unit-enum key order.
11//! Secondary indexes admit integers, Ulid, Date, Timestamp, Duration, Decimal, finite floats,
12//! Account/Subaccount, Principal, Bool, Text, Blob and unit enums, including optional values; primary keys
13//! require non-optional integer, U256, Ulid, Principal, Account or Subaccount fields. References use
14//! the target’s exact key type;
15//! absence has no target, while every present target must survive the batch.
16//! Atomicity relies on the enclosing IC message: after persistent mutation starts,
17//! supplier failures trap. A later application trap also rolls back the batch.
18//! Native callers must discard their runtime after a mutation panic. No SQL,
19//! endpoint exports, automatic migration or production compatibility is promised.
20//!
21//! Payload enums cannot become index keys, even when a row selects a unit variant:
22//! ```compile_fail
23//! use ic_db::{entity, enum_};
24//! #[enum_(variant(name="Empty"), variant(name="Data", value(item(prim="Nat8"))))]
25//! struct State {}
26//! #[entity(pk(field="id"), index(field="state"), fields(
27//!     field(name="id", value(item(prim="Nat64"))),
28//!     field(name="state", value(opt, item(is="State")))
29//! ))]
30//! struct Row {}
31//! ```
32//! Payload enums also lack the generated ordering required by sets/maps:
33//! ```compile_fail
34//! use ic_db::{enum_, set};
35//! #[enum_(variant(name="Empty"), variant(name="Data", value(item(prim="Nat8"))))]
36//! struct State {}
37//! #[set(item(is="State"), max_items=3)]
38//! struct States {}
39//! ```
40
41#[doc(hidden)]
42mod codec;
43mod date;
44mod decimal;
45mod defaults;
46mod float;
47mod key;
48mod managed;
49mod primary;
50mod schema;
51mod session;
52mod store;
53mod store_key;
54mod time;
55mod types;
56mod ulid;
57
58#[cfg(all(feature = "build", not(target_arch = "wasm32")))]
59pub mod build;
60
61#[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
62pub mod testing;
63
64#[doc(hidden)]
65#[cfg(any(rust_analyzer, not(feature = "build"), target_arch = "wasm32"))]
66#[macro_export]
67macro_rules! __register_schema {
68    ($entity:ident) => {};
69}
70
71pub use date::Date;
72pub use decimal::{Decimal, ParseDecimalError};
73pub use defaults::{InsertInput, LiteralDefault};
74/// Exact unsigned 256-bit integer. IC DB owns its durable and index encodings.
75pub use ethnum::U256;
76pub use float::{Float32, Float64};
77pub use ic_db_macros::{entity, enum_, list, map, newtype, record, set};
78pub use ic_platform_types::{Account, Principal, Subaccount};
79pub use key::IndexValue;
80pub use managed::ManagedTimestamp;
81pub use primary::PrimaryKey;
82pub use time::{Duration, TimeParseError, Timestamp};
83pub use ulid::{
84    SeededUlidGenerator, Ulid, UlidEntropyError, UlidGenerationError, UlidGenerator, UlidParseError,
85};
86/// Owned binary bytes. The database codec enforces authored limits and row bounds.
87pub type Blob = Vec<u8>;
88pub use schema::{EntitySchema, FieldSchema, FieldType, IndexSchema, ReferenceSchema, Schema};
89pub use session::{DatabaseSession, UniqueKey};
90pub use store::{
91    Aggregate, Batch, Comparison, CopyStatus, CopyStep, GroupCount, GroupCursor, GroupOrder,
92    GroupPage, GroupValue, JobHandle, JobOutcome, JobStep, Page, QueryCursor, QueryOperand,
93    QueryPage, SchemaTransition, SortDirection,
94};
95
96/// Admitted database owning an exclusive lease on a named IC Storage allocation.
97pub type Database = store::Database<ic_storage::DefaultMemoryImpl>;
98/// Fluent query over an entity in the admitted database.
99pub type Query<'a, E> = store::Query<'a, E, ic_storage::DefaultMemoryImpl>;
100/// Exclusive handle to a frozen source during maintenance.
101pub type Maintenance = store::Maintenance<ic_storage::DefaultMemoryImpl>;
102/// Bounded retained aggregates in their host-governed allocation.
103pub type AggregateJobs = store::AggregateJobs<ic_storage::DefaultMemoryImpl>;
104/// In-progress transformation into an identified target allocation.
105pub type SchemaCopy = store::SchemaCopy<ic_storage::DefaultMemoryImpl>;
106/// Retired source allocation held for bounded cleanup.
107pub type RetiredSource = store::RetiredSource<ic_storage::DefaultMemoryImpl>;
108
109/// Implementation methods for the concrete database handles. Installed Wasm
110/// fault probes enable `test-support` to specialize these handles for their backing.
111#[cfg(any(doc, feature = "test-support"))]
112pub mod qualification {
113    pub use crate::store::{
114        AggregateJobs, Database, Maintenance, Query, RetiredSource, SchemaCopy,
115    };
116}
117pub use store_key::MAX_INDEX_KEY_BYTES;
118
119/// Failure before commit begins, or a refusal to admit stored data.
120#[derive(Debug)]
121pub enum Error {
122    /// A session operation conflicts with an active borrow of the attached database.
123    BorrowConflict,
124    /// Ordinary access is closed by an admitted durable maintenance gate.
125    Maintenance,
126    /// A maintenance identity is invalid or does not match this source/active transition.
127    InvalidTransition,
128    /// The retained job handle, query, result shape or requested sequence does not match.
129    InvalidJob,
130    /// All retained job slots are occupied; cancel or clean up expired jobs explicitly.
131    JobCapacity,
132    /// An arithmetic total exceeds its accumulator or explicitly selected result range.
133    ArithmeticOverflow,
134    /// Unsupported query field/shape or unavailable ordered access path.
135    InvalidQuery,
136    /// A query requiring at most one matching entity found a second.
137    MultipleMatches,
138    /// Malformed continuation or a different database/schema/query boundary.
139    InvalidCursor,
140    /// One matching encoded row exceeds the whole requested output-byte allowance.
141    RowTooLarge,
142    /// Managed insert/replacement requires an explicitly captured batch time.
143    MissingOperationTime,
144    /// A caller attempted to assign a database-managed field.
145    ManagedField,
146    /// A real change would move managed time behind its stored value.
147    TimestampRegression,
148    /// An insert input omitted a required field with no declared default.
149    MissingField(&'static str),
150    /// Invalid or unsupported compiled schema.
151    InvalidSchema,
152    /// An index operand has a different exact type from its declared field.
153    InvalidOperand,
154    /// The typed entity is not part of this admitted schema.
155    UnknownEntity,
156    /// The stored manifest belongs to another schema or format.
157    IncompatibleSchema,
158    /// Missing, malformed or internally inconsistent stored data.
159    Corrupt,
160    /// Insert requires an absent primary key.
161    Exists,
162    /// Replacement/deletion requires an existing primary key.
163    Missing,
164    /// Two batch commands address the same entity and primary key.
165    DuplicateTarget,
166    /// The intended final state violates a unique index.
167    UniqueViolation,
168    /// A reference target is absent, or a deleted target still has a dependent.
169    ReferenceViolation,
170    /// A declared resource bound or revision range is exceeded.
171    Limit,
172}
173
174impl std::fmt::Display for Error {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        write!(f, "{self:?}")
177    }
178}
179impl std::error::Error for Error {}
180
181pub use types::{TypeBody, TypeLink, TypeSchema, Value, ValueSchema, VariantSchema};
182
183/// Schema authoring for application design modules.
184pub mod design {
185    /// Declaration attributes, database scalar types and schema assembly.
186    ///
187    /// ```
188    /// use ic_db::design::prelude::*;
189    ///
190    /// #[newtype(item(prim = "Timestamp"))]
191    /// struct StartedAt {}
192    ///
193    /// #[list(item(is = "StartedAt"), max_items = 3)]
194    /// struct StartHistory {}
195    ///
196    /// #[entity(pk(field = "id"), fields(
197    ///     field(name = "id", value(item(prim = "Nat64"))),
198    ///     field(name = "history", value(item(is = "StartHistory")))
199    /// ))]
200    /// struct Event {}
201    ///
202    /// let event = Event { id: 1, history: StartHistory(vec![StartedAt(Timestamp::from_millis(0))]) };
203    /// let schema = Schema::new(&[Event::SCHEMA]).unwrap();
204    /// assert_eq!(schema.entities()[0].name, "Event");
205    /// assert_eq!(event.history.0.len(), 1);
206    /// ```
207    pub mod prelude {
208        pub use crate::{
209            Account, Blob, Date, Decimal, Duration, Float32, Float64, Principal, Subaccount,
210            Timestamp, U256, Ulid,
211        };
212        pub use crate::{Entity, Schema, Value};
213        pub use crate::{entity, enum_, list, map, newtype, record, set};
214    }
215}
216
217/// Codec boundary emitted by `#[entity]`; hand-written implementations are unsupported.
218/// Typed references use Rust resolution; an unresolved name fails compilation:
219/// ```compile_fail
220/// use ic_db::entity;
221/// #[entity(pk(field="id"), index(field="target"), fields(
222///     field(name="id",value(item(prim="Nat64"))),
223///     field(name="target",value(item(prim="Nat64")),references(entity="Missing"))))]
224/// struct Example {}
225/// ```
226/// Lookups require the declared key type; integers cannot stand in for ULIDs:
227/// ```compile_fail
228/// use ic_db::{entity, Database};
229/// #[entity(pk(field="id"), fields(field(name="id",value(item(prim="Ulid")))))]
230/// struct Asset {}
231/// fn wrong_key(db: &Database) { let _ = db.get::<Asset>(7_u64); }
232/// ```
233/// Integer key widths are exact, without implicit widening:
234/// ```compile_fail
235/// use ic_db::{entity, Database};
236/// #[entity(pk(field="id"), fields(field(name="id",value(item(prim="Nat8")))))]
237/// struct Small {}
238/// fn wrong_width(db: &Database) { let _ = db.get::<Small>(7_u64); }
239/// ```
240/// Field names come from the declaration. A missing `name` field cannot
241/// resolve to the entity's logical name, even when `Entity` is in scope.
242/// ```compile_fail
243/// use ic_db::{entity, Entity};
244/// #[entity(pk(field="id"), fields(field(name="id", value(item(prim="Nat64")))))]
245/// struct Entry {}
246/// let _ = Entry::NAME;
247/// ```
248/// ```compile_fail
249/// use ic_db::{entity, Entity};
250/// #[entity(pk(field="id"), fields(field(name="id", value(item(prim="Nat64")))))]
251/// struct Entry {}
252/// let _ = Entry::ENTITY_NAME;
253/// ```
254pub trait Entity: Sized {
255    /// Exact supplied primary-key type, selected by the declared field.
256    type Key: PrimaryKey;
257    /// Rust-resolved declaration path for host schema assembly.
258    fn declaration_path() -> &'static str;
259    /// This executable's compiled entity contract.
260    const SCHEMA: &'static EntitySchema;
261    /// Read the application's primary key without encoding or inspecting indexes.
262    fn key(&self) -> Self::Key;
263
264    /// Extract keys from an already typed value for the shared mutation/index paths.
265    #[doc(hidden)]
266    fn __row_info(&self) -> __private::RowInfo;
267
268    /// Validate declared field bounds before encoding; no persistent effects.
269    /// # Errors
270    /// Refuses values outside the authored field contract.
271    fn validate(&self) -> Result<(), Error>;
272
273    /// Encode canonical stored fields within the row envelope.
274    /// # Errors
275    /// Returns a limit refusal when the row cannot be encoded within its bounds.
276    fn encode(&self) -> Result<Vec<u8>, Error>;
277
278    /// Decode an admitted row; this does not open a database or admit a schema.
279    /// # Errors
280    /// Returns corruption for malformed stored bytes.
281    fn decode(bytes: &[u8]) -> Result<Self, Error>;
282}
283
284/// Implementation support for generated code; not a second query frontend.
285#[doc(hidden)]
286pub mod __private {
287    pub use serde;
288    /// Independent of the descriptor so references can form cycles.
289    pub trait ReferenceTarget {
290        /// Schema-authored logical name of the target entity.
291        const NAME: &'static str;
292    }
293    pub use crate::codec::{Decoder, Encoder, MAX_ROW_BYTES};
294    pub use crate::key::encode_index;
295    pub use crate::managed::validate_order as validate_managed_order;
296    pub use crate::primary::RowKey;
297    pub use crate::schema::handle;
298    /// Primary/index keys extracted at the small typed codec boundary.
299    pub struct RowInfo {
300        pub key: RowKey,
301        /// None means the row is outside an explicitly present-only unique index.
302        pub indexes: Vec<Option<Vec<u8>>>,
303    }
304}