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