Skip to main content

Crate ic_dbms_canister

Crate ic_dbms_canister 

Source
Expand description

§IC DBMS Canister

The ic-dbms-canister crate provides a database management system (DBMS) canister for the Internet Computer (IC).

You can create a database canister by just defining your data tables using Rust structs and deriving the Table trait.

§Usage

§Add dependencies

[dependencies]
candid = { version = "0.10", features = ["value"] }
ic-cdk = "0.20"
ic-dbms-api = "0.10"
ic-dbms-canister = { version = "0.10", features = ["sql"] }
serde = "1"

§Define Tables

use candid::CandidType;
use ic_dbms_api::prelude::{Nullable, Text, Uint32, Uint64};
use ic_dbms_canister::prelude::{DatabaseSchema, DbmsCanister, Table};
use serde::Deserialize;

// define a simple `User` table

#[derive(Debug, Table, CandidType, Deserialize, Clone, PartialEq, Eq)]
#[candid]
#[table = "users"]
pub struct User {
    #[primary_key]
    id: Uint64,
    name: Text,
    email: Text,
    age: Nullable<Uint32>,
}

// define a table referencing `User`

#[derive(Debug, Table, CandidType, Deserialize, Clone, PartialEq, Eq)]
#[candid]
#[table = "posts"]
pub struct Post {
    #[primary_key]
    id: Uint32,
    title: Text,
    content: Text,
    #[foreign_key(entity = "User", table = "users", column = "id")]
    author: Uint32,
}

// Finally define the schema. This will generate the API for the canister.

#[derive(DatabaseSchema, DbmsCanister)]
#[tables(User = "users", Post = "posts")]
pub struct IcDbmsCanisterGenerator;

This will generate the following API:

service : (IcDbmsCanisterArgs) -> {
  acl_grant : (AclGrant) -> (Result);
  acl_list : () -> (Result_4) query;
  acl_revoke : (AclGrant) -> (Result);
  begin_transaction : () -> (Result_6);
  commit : (nat64) -> (Result);
  delete_posts : (DeleteBehavior, opt Filter_1, opt nat64) -> (Result_1);
  delete_users : (DeleteBehavior, opt Filter_1, opt nat64) -> (Result_1);
  insert_posts : (PostInsertRequest, opt nat64) -> (Result);
  insert_users : (UserInsertRequest, opt nat64) -> (Result);
  my_permissions : () -> (Result_5) query;
  rollback : (nat64) -> (Result);
  sql : (text, vec Value, opt nat64) -> (Result_7);
  sql_query : (text, vec Value, opt nat64) -> (Result_7) query;
  select_posts : (Query, opt nat64) -> (Result_2) query;
  select_users : (Query_1, opt nat64) -> (Result_3) query;
  update_posts : (PostUpdateRequest, opt nat64) -> (Result_1);
  update_users : (UserUpdateRequest, opt nat64) -> (Result_1);
}

§API Documentation

The API generated by the ic-dbms-canister is the following:

§Access Control

Every endpoint except my_permissions checks the caller’s grants, stored in the reserved ic_dbms_acl table. A grant is a principal, an AclPermission (Admin, Read, Insert, Update, Delete) and an optional table; no table means every table. Admin allows everything.

  • acl_grant(grant): Stores a grant. Requires Admin. Idempotent.
  • acl_revoke(grant): Removes a grant. Requires Admin. The last admin cannot be revoked.
  • acl_list(): Lists every grant. Requires Admin.
  • my_permissions(): Returns the caller’s grants. Allowed for everyone.

§Transaction Management

  • begin_transaction(): Starts a new transaction and returns its ID. The caller must hold at least one grant.
  • commit(transaction_id): Commits the transaction with the given ID. The user must own the transaction to commit it.
  • rollback(transaction_id): Rolls back the transaction with the given ID. The user must own the transaction to roll it back.
  • Ownership is tracked on the canister heap and cleared by the generated pre_upgrade hook. Open transactions do not survive upgrades.

§Data Manipulation

For each table defined in the schema, the following methods are generated:

  • insert_<table_name>(records, transaction_id): Inserts records into the specified table. Optionally within a transaction.
  • select_<table_name>(query, transaction_id): Selects records from the specified table based on the query. Optionally within a transaction.
  • update_<table_name>(updates, transaction_id): Updates records in the specified table. Optionally within a transaction.
  • delete_<table_name>(delete_behavior, filter, transaction_id): Deletes records from the specified table based on the filter and delete behavior. Optionally within a transaction.

§SQL (sql feature)

Enable the sql feature of ic-dbms-canister to also generate:

  • sql(query, params, transaction_id): Runs one SQL statement (update call). BEGIN returns a transaction ID to pass to later statements.
  • sql_query(query, params, transaction_id): Runs one SELECT statement (query call) and refuses every other statement.

Statements are checked against the access control list like the typed endpoints, and tables reserved for ic-dbms are not visible to SQL.

§Feature flags

namedescriptiondefault
sqlGenerate SQL endpoints and include the SQL execution engine.

§Interacting with the Canister

See the ic-dbms-client crate for a client library to interact with the canister.

§How Internet Computer Memory Works

On the Internet Computer, canisters have access to a stable memory that persists across upgrades. This stable memory is divided into pages, each of which is 64 KiB in size.

When a canister is first created, it starts with a small amount of stable memory, and it can grow this memory as needed by allocating additional pages. The canister can read from and write to this stable memory using specific APIs provided by the Internet Computer SDK.

§Memory Model

---
title: "Memory Model"
---
packet
+32: "Schema Table (65k)"
+32: "Unclaimed Pages Ledger (65k)"
+16: "Table XX Page Ledger (65k)"
+16: "Table XX Free Segments Ledger (65k)"
+16: "Table YY Page Ledger (65k)"
+16: "Table YY Free Segments Ledger (65k)"
+32: "Table XX Records - Page 1 (65k)"
+32: "Table XX Records - Page 2 (65k)"
+32: "Table YY Records - Page 1 (65k)"
+32: "Table XX Records - Page 3 (65k)"
+32: "Table YY Records - Page 2 (65k)"

Modules§

acl
Access control list stored in the reserved ic_dbms_acl table.
api
Generic per-operation helpers consumed by the endpoints generated by #[derive(DbmsCanister)].
prelude
Re-exports all the most commonly used items from this crate.
schema
Composition of the user schema with the reserved tables.
transaction
Heap-only ledger from transaction ID to the principal that opened it.
utils

Macros§

trap
A macro for trapping the canister execution.