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