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