#![forbid(unsafe_code)]
#[cfg(feature = "logging")]
pub mod logging;
#[cfg(feature = "metrics")]
pub mod metrics;
#[cfg(feature = "metrics")]
macro_rules! observe_metrics {
($kind:ident, $body:block) => {
crate::metrics::$kind(|| $body)
};
}
#[cfg(not(feature = "metrics"))]
macro_rules! observe_metrics {
($kind:ident, $body:block) => {
$body
};
}
macro_rules! observe {
($kind:ident, $body:block) => {{
#[cfg(feature = "logging")]
{
crate::logging::observe(concat!("ic-db.", stringify!($kind)), || {
observe_metrics!($kind, $body)
})
}
#[cfg(not(feature = "logging"))]
{
observe_metrics!($kind, $body)
}
}};
}
mod canister_session;
mod clock;
#[doc(hidden)]
mod codec;
mod date;
mod decimal;
mod defaults;
mod float;
mod key;
mod managed;
mod member;
mod primary;
mod schema;
mod session;
mod store;
mod store_key;
mod time;
mod types;
mod u256;
mod ulid;
#[cfg(feature = "wire")]
mod wire;
#[cfg(all(feature = "build", not(target_arch = "wasm32")))]
mod build;
#[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
pub mod testing;
pub use canister_session::{CanisterSession, MountedStore, StoreBatch};
pub use date::Date;
pub use decimal::{Decimal, ParseDecimalError};
pub use defaults::{InsertInput, LiteralDefault};
pub use float::{Float32, Float64};
pub use ic_db_macros::{canister, entity, enum_, list, map, newtype, record, set, store};
pub use ic_platform_types::{Account, Principal, Subaccount};
pub use key::IndexValue;
pub use managed::ManagedTimestamp;
pub use primary::PrimaryKey;
pub use schema::{EntitySchema, FieldSchema, FieldType, IndexSchema, ReferenceSchema, Schema};
pub use session::{DatabaseSession, QuerySession, UniqueKey};
pub use store::{
Aggregate, Batch, Comparison, CopyStatus, CopyStep, GroupCount, GroupCursor, GroupOrder,
GroupPage, GroupSummaries, GroupSummary, GroupSummaryPage, GroupValue, JobHandle, JobOutcome,
JobStep, Page, QueryCursor, QueryOperand, QueryPage, SchemaTransition, SortDirection,
SummaryMeasure,
};
pub use store_key::MAX_INDEX_KEY_BYTES;
pub use time::{Duration, TimeParseError, Timestamp};
pub use types::{TypeBody, TypeLink, TypeSchema, Value, ValueSchema, VariantSchema};
pub use u256::U256;
pub use ulid::{
SeededUlidGenerator, Ulid, UlidEntropyError, UlidGenerationError, UlidGenerator, UlidParseError,
};
#[doc(hidden)]
#[cfg(any(not(feature = "build"), target_arch = "wasm32"))]
#[macro_export]
macro_rules! __register_schema {
($($declaration:tt)*) => {};
}
#[doc(hidden)]
#[cfg(not(feature = "wire"))]
#[macro_export]
macro_rules! __wire_as {
($value:ty, $layout:ty) => {};
}
#[macro_export]
macro_rules! include_schema {
() => {
::core::include!(::core::concat!(::core::env!("OUT_DIR"), "/schema.rs"));
};
}
pub trait Canister {
#[doc(hidden)]
const DECLARATION: &'static str;
}
pub trait Store {
type Canister: Canister;
const KEY: &'static str;
#[doc(hidden)]
const DECLARATION: &'static str;
}
pub trait CompiledCanister: Canister {
const STORES: &'static [CompiledStore];
}
pub struct CompiledStore {
pub key: &'static str,
pub schema: fn() -> Schema,
}
pub type Blob = Vec<u8>;
pub type Database = store::Database<ic_storage::DefaultMemoryImpl>;
pub type Query<'a, E> = store::Query<'a, E, ic_storage::DefaultMemoryImpl>;
pub type Maintenance = store::Maintenance<ic_storage::DefaultMemoryImpl>;
pub type AggregateJobs = store::AggregateJobs<ic_storage::DefaultMemoryImpl>;
pub type SchemaCopy = store::SchemaCopy<ic_storage::DefaultMemoryImpl>;
pub type RetiredSource = store::RetiredSource<ic_storage::DefaultMemoryImpl>;
#[cfg(any(doc, feature = "test-support"))]
pub mod qualification {
pub use crate::store::{
AggregateJobs, Database, Maintenance, Query, RetiredSource, SchemaCopy,
};
}
#[derive(Debug)]
pub enum Error {
BorrowConflict,
Maintenance,
InvalidTransition,
InvalidJob,
JobCapacity,
ArithmeticOverflow,
InvalidQuery,
MultipleMatches,
InvalidCursor,
RowTooLarge,
MissingOperationTime,
ManagedField,
TimestampRegression,
MissingField(&'static str),
InvalidSchema,
InvalidOperand,
UnknownEntity,
IncompatibleSchema,
Corrupt,
Exists,
Missing,
DuplicateTarget,
UniqueViolation,
ReferenceViolation,
Limit,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for Error {}
pub mod design {
pub mod prelude {
pub use crate::{
Account, Blob, Date, Decimal, Duration, Float32, Float64, Principal, Subaccount,
Timestamp, U256, Ulid,
};
pub use crate::{Canister, CompiledCanister, Entity, Schema, Store, Value};
pub use crate::{canister, entity, enum_, list, map, newtype, record, set, store};
}
}
pub trait Entity: Sized {
type Store: Store;
type Key: PrimaryKey;
fn declaration_path() -> &'static str;
const SCHEMA: &'static EntitySchema;
fn key(&self) -> Self::Key;
#[doc(hidden)]
fn __row_info(&self) -> __private::RowInfo;
fn validate(&self) -> Result<(), Error>;
fn encode(&self) -> Result<Vec<u8>, Error>;
fn decode(bytes: &[u8]) -> Result<Self, Error>;
}
#[doc(hidden)]
pub mod __private {
#[cfg(all(feature = "build", not(target_arch = "wasm32")))]
pub use crate::build::{__build_schema, __canister, __ctor, __entity, __store};
#[cfg(not(feature = "wire"))]
pub use ic_db_macros::__StorageOnly as Wire;
#[cfg(feature = "wire")]
pub use ic_wire::{self, typescript::Wire};
pub use serde;
pub trait ReferenceTarget {
const NAME: &'static str;
}
pub use crate::codec::{Decoder, Encoder, MAX_ROW_BYTES};
pub use crate::key::{MemberOperand, encode_index};
pub use crate::managed::validate_order as validate_managed_order;
pub use crate::primary::RowKey;
pub use crate::schema::{check_schema_member, handle};
pub struct RowInfo {
pub key: RowKey,
pub indexes: Vec<Option<Vec<u8>>>,
}
}
#[macro_export]
macro_rules! field_path {
($record:path, $member:path $(,)?) => {{
const BYTES: [u8; $record.len() + 1 + $member.len()] = {
let mut bytes = [0; $record.len() + 1 + $member.len()];
let (parent, tail) = bytes.split_at_mut($record.len());
parent.copy_from_slice($record.as_bytes());
tail[0] = b'.';
tail.split_at_mut(1).1.copy_from_slice($member.as_bytes());
bytes
};
const {
match ::core::str::from_utf8(&BYTES) {
Ok(path) => path,
Err(_) => panic!("invalid field name"),
}
}
}};
}