Expand description
Experimental IC database: compiled schemas and synchronous bounded records.
Schema modules can import the declaration attributes and value types from
design::prelude.
This M1 slice supports 8/16/32/64/128-bit integers, U256, Ulid, Date, Timestamp, Duration, Decimal, finite Float32/Float64, Bool, Principal, Account/Subaccount and bounded Text/Blob, with optional values. Named records and unit/payload enums support bounded recursion via explicit indirection and ordered lists; traversals share byte, depth, structured-value and total collection-item limits. Sets/maps use strict scalar/unit-enum key order. Secondary indexes admit integers, Ulid, Date, Timestamp, Duration, Decimal, finite floats, Account/Subaccount, Principal, Bool, Text, Blob and unit enums, including optional values; primary keys require non-optional integer, U256, Ulid, Principal, Account or Subaccount fields. References use the target’s exact key type; absence has no target, while every present target must survive the batch. Atomicity relies on the enclosing IC message: after persistent mutation starts, supplier failures trap. A later application trap also rolls back the batch. Native callers must discard their runtime after a mutation panic. No SQL, endpoint exports, automatic migration or production compatibility is promised.
Payload enums cannot become index keys, even when a row selects a unit variant:
use ic_db::design::prelude::*;
#[enum_(variant(name="Empty"), variant(name="Data", value(item(prim="Nat8"))))]
struct State {}
#[entity(store = ic_db::testing::FixtureStore, pk(field="id"), index(field="state"), fields(
field(name="id", value(item(prim="Nat64"))),
field(name="state", value(opt, item(is="State")))
))]
struct Row {}Payload enums also lack the generated ordering required by sets/maps:
use ic_db::design::prelude::*;
#[enum_(variant(name="Empty"), variant(name="Data", value(item(prim="Nat8"))))]
struct State {}
#[set(item(is="State"), max_items=3)]
struct States {}Re-exports§
pub use canister_session::CanisterSession;pub use canister_session::StoreBatch;pub use types::NonAnonymousPrincipal;
Modules§
- design
- Schema authoring for application design modules.
- qualification
- Implementation methods for the concrete database handles. Installed Wasm
fault probes enable
test-supportto specialize these handles for their backing. - types
- Reusable named values for application schemas.
Macros§
- field_
path - Join two generated field-name constants for a scalar record member.
For example,
ic_db::field_path!(Product::PRICE, Price::AMOUNT)is a static field name accepted by scalar literal filters and row ordering. - include_
schema - Include the schema assembly generated by this package’s build script.
Invoke once at the crate root alongside the declarations compiled by
ic_db::build_schema!. Consumers import the resulting types from that crate.
Structs§
- Account
- Account A Principal owner and optional subaccount.
- Aggregate
- A completed aggregate and its execution costs. No partial result or cursor.
- Batch
- A bounded synchronous batch; preparation is internal to
Database::commit. - Canister
Session - All store sessions for one declared canister. Clones share the same leases.
- Column
- A column of entity
Ewhose stored value decodes toT. - Compiled
Store - Validated schema and its stable allocation key.
- Copy
Step - A bounded copy result. Completion means all source rows were copied, not that the target is validated for publication or available for ordinary access.
- Database
Session - A cloneable handle to one attached database and its existing storage lease.
The host attaches once using
Self::newand hands each caller a clone. Cloning takes no database borrow and performs no storage access. - Date
- A Gregorian calendar date, stored as days since the Unix epoch.
- Decimal
- Exact base-ten value with a signed 128-bit mantissa and scale 0–28. Construction removes fractional trailing zeros; all zero values share one representation. No floating-point conversion or implicit rounding is used.
- Duration
- Nonnegative millisecond duration. Constructors from larger units and arithmetic operators saturate; text parsing refuses overflow. No clock or timer is owned.
- Entity
Schema - Compiled entity metadata emitted by the entity macro.
- Field
Schema - One named stored field; type, bounds, optionality and write policy define identity.
- Float32
- Finite canonical
f32. Construction normalizes negative zero; NaN and infinities refuse. - Float64
- Finite canonical
f64. Construction normalizes negative zero; NaN and infinities refuse. - Group
Count - One complete group. Absent optional key values belong to a group too.
- Group
Cursor - Logical position in one completed retained job, not an authorization token. Positions are revalidated against the selected result; caller edits can skip rows intentionally but cannot change the result or advance input progress.
- Group
Page - One page of completed retained groups. Keep
nextwhen mappingrows. - Group
Summary - Count, sum and average of one numeric operand in a completed group.
- Group
Value - One complete group’s aggregate value, preserving all-absent groups.
- Id
- An application key branded with the entity that owns it. Constructing one does not read storage or prove that the row exists. An ID for one entity cannot address another entity with the same raw key.
- Index
Schema - A compiled index over supported exact scalar components.
- JobHandle
- Opaque retained-job identity. The host must check caller authorization separately.
- JobStep
- Saved progress. Older sequences do not rescan; revision and expiry checks still apply.
- Page
- A bounded page of rows in live primary-key order.
- Parse
Decimal Error - Invalid syntax or a value outside Decimal’s exact coefficient/scale domain.
- Principal
- Principal An opaque IC identity containing at most 29 significant bytes.
- Query
Cursor - A bounded logical position, bound to database, schema, query and direction. It is not an authorization token or a snapshot. Callers may choose positions; the database revalidates all claims and retains no trusted progress counters.
- Query
Page - A bounded page. Empty rows do not mean completion when
nextis present. Ordinary queries are live; maintenance source pages read frozen input. - Reference
Schema - A required or optional typed reference using an ordinary reverse-lookup index. An absent optional value has no target; zero remains an ordinary target key.
- Schema
- Validated executable schema. It is never reconstructed from stored data. Clones retain only immutable executable metadata; each database open still validates the current durable manifest independently. Revision reads and writes validate the affected counters when used, without caching them.
- Schema
Description - Serializable inspection of one compiled store or a single entity in it.
- Schema
Transition - Identity of one explicitly supported source-to-target transformation. Changing code behavior requires a new version, even when both schemas match. This descriptor does not execute a transformation or authorize target publication.
- Seeded
Ulid Generator - A canister-owned or application-owned sequence seeded once at creation. Each newer millisecond starts at the stream’s seed. IDs are predictable.
- Selected
Query - A bounded query with its result columns selected.
- Store
Batch - A synchronous batch bound to one mounted store. Dropping it discards its prepared changes.
- Timestamp
- Signed Unix-millisecond timestamp, including instants before 1970. Sub-millisecond conversions floor; arithmetic operators saturate only after the complete wide operation.
- Type
Link - Compiler-resolved link. Names carry identity; the function breaks constant cycles.
- Type
Schema - Named schema; its links are shallow so recursive graphs never expand on comparison.
- U256
- Unsigned 256-bit integer, encoded as a hexadecimal quantity by Serde.
- Ulid
- A 128-bit ULID with exact 16-byte storage and canonical uppercase text.
- Ulid
Generator - Monotonic ULIDs for one explicitly owned issuance stream.
- Ulid
Parse Error - Text was not an exact canonical uppercase 26-character ULID.
- Value
Schema - Payload shape, shared with the field type/optionality rules.
- Variant
Schema - One unit or payload variant.
Enums§
- Comparison
- Exact comparison. Equality distinguishes absent values; ranges and pattern matches require presence.
- Copy
Status - Current stage of an admitted schema copy, derived from its saved checkpoint.
- Error
- Failure before commit begins, or a refusal to admit stored data.
- Field
Type - Stored value semantics supported by this increment.
- Group
Order - Completed-group ordering. Aggregate ties always use ascending canonical keys.
- Index
Value - One exact ordered scalar operand for index prefixes and fluent comparisons. Operand types must match declared fields; integers are never implicitly widened, narrowed or coerced across signedness. This is a bounded scalar boundary, not a general expression/value representation.
- Insert
Outcome - Result of inserting one input conditionally on its declared unique index.
- JobOutcome
- Only Complete contains a result. Running never exposes a prefix as an exact total.
- Literal
Default - A compiled literal used only when an insert input omits its field. These are schema constants, not a dynamic query or mutation value model.
- Managed
Timestamp - Database-owned timestamp assignment during bounded write preparation.
- Newtype
Rule - A versioned constraint on the inner primitive of a named newtype.
- Query
Operand - A literal, row field or length threshold in a fluent predicate.
- Sort
Direction - Direction of one field in an explicit result order.
- Summary
Measure - Numeric result used to order completed summary groups.
- Time
Parse Error - Invalid or out-of-range human-readable time input.
- Type
Body - A compiled named type; record/enum members use canonical name order.
- Ulid
Entropy Error - Failure to obtain fresh entropy for a ULID.
- Ulid
Generation Error - A refused issuance; the generator’s previous state remains unchanged.
Constants§
- MAX_
INDEX_ KEY_ BYTES - Maximum complete encoded secondary-index key, including namespace and owner suffix.
Traits§
- Canister
- Logical database owner. Deployment and memory grants belong to the host.
- Compiled
Canister - Host-facing assembly generated in the schema owner’s library.
- Entity
- Codec boundary emitted by
#[entity]; hand-written implementations are unsupported. Typed references use Rust resolution; an unresolved name fails compilation: - Insert
Input - Typed insert construction with omission distinct from explicit optional absence.
Generated inputs implement this once per entity; execution stays in
Batch. Managed fields have no input setters: - Primary
Key - Supported supplied primary key: integers, U256, Ulid, Principal, Account or Subaccount. This sealed boundary keeps lookup/delete/page arguments typed to their entity.
- Query
Session - A session that can start a fluent query for
E. Generic read helpers can accept either a store session or the session for the entity’s canister. - Select
Columns - Field handles supplied to a selection by an authored entity.
- Selection
- A single selected column or a tuple of two to four columns from one entity.
- Store
- Logical store and the stable allocation it uses within its canister.
- Unique
Key - Named lookup components generated for a declared unique index.
- Value
- Codec boundary generated by named-type macros; handwritten implementations are unsupported.
Type Aliases§
- Aggregate
Jobs - Bounded retained aggregates in their host-governed allocation.
- Blob
- Owned binary bytes. The database codec enforces authored limits and row bounds.
- Database
- Admitted database owning an exclusive lease on a named IC Storage allocation.
- Group
Summaries - Completed numeric summaries and the work of their shared scan.
- Group
Summary Page - A page of completed retained numeric summaries.
- Maintenance
- Exclusive handle to a frozen source during maintenance.
- Query
- Fluent query over an entity in the admitted database.
- Retired
Source - Retired source allocation held for bounded cleanup.
- Schema
Copy - In-progress transformation into an identified target allocation.
- Subaccount
- Opaque application-owned subaccount bytes.
Attribute Macros§
- canister
- Declare a logical database canister.
- entity
- Author a typed record with named fields, a supplied scalar key and indexes.
- enum_
- Declare a named enum using an empty struct and
variant(name = "...")attributes. Supports 1–64 unit or typed payload variants. Canonical name order determines stored ordinals; source declaration order does not. Use item(indirect, is = “Self”) for boxed recursion, with a finite base alternative. All-unit enums also convert by reference intoic_db::IndexValue, using the same canonical order. Any payload variant excludes the whole enum from indexes. - list
- Declare a reusable ordered list with an item type and a shared maximum length.
- map
- Declare a named
BTreeMapwrapper usingkey(...),value(...)andmax_items = N(0..256). Keys are primitives, scalar newtypes or unit enums. Values use the ordinary optional/list/named field rules; stored duplicate keys refuse. - newtype
- Declare a distinct Rust and schema type around one primitive, including its bounds.
Serde uses the wrapped value directly by default.
A Principal newtype can use
validate(non_anonymous)and be constructed viaTryFrom<Principal>. - record
- Declare a named stored record using attribute-owned fields and an empty struct.
- set
- Declare a bounded ordered set with
item(...)andmax_items = N(0..256). Elements can be primitives, scalar newtypes or unit enums. The generated wrapper contains aBTreeSet<T>. Decoding requires strictly increasing keys. - store
- Declare a store with a typed canister owner and an IC Storage allocation key.