Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Client API (IC)

Note: This is the IC-specific client API guide. For general wasm-dbms documentation, see the generic docs.


Overview

The ic-dbms-client crate provides type-safe Rust clients for interacting with ic-dbms canisters. Instead of manually constructing Candid calls, you use a high-level API that handles serialization and error handling.

Benefits:

  • Type-safe operations with compile-time checking
  • Automatic Candid encoding/decoding
  • Consistent API across different environments
  • Built-in error handling

Client Types

ic-dbms provides three client implementations for different use cases:

ClientUse CaseFeature Flag
IcDbmsCanisterClientInter-canister calls (inside IC canisters)Default
IcDbmsAgentClientExternal applications (frontend, backend, CLI)ic-agent
IcDbmsPocketIcClientIntegration tests with PocketICpocket-ic

IcDbmsCanisterClient

For calls from one IC canister to another:

#![allow(unused)]
fn main() {
use ic_dbms_client::prelude::{IcDbmsCanisterClient, Client as _};
use candid::Principal;

// In your canister code
let dbms_canister_id = Principal::from_text("rrkah-fqaaa-aaaaa-aaaaq-cai").unwrap();
let client = IcDbmsCanisterClient::new(dbms_canister_id);

// Use the client
let users = client.select::<User>(User::table_name(), query, None).await??;
}

IcDbmsAgentClient

For external applications using the IC Agent:

#![allow(unused)]
fn main() {
use ic_dbms_client::prelude::{IcDbmsAgentClient, Client as _};
use ic_agent::Agent;
use candid::Principal;

// Create an IC Agent (with identity, etc.)
let agent = Agent::builder()
    .with_url("https://ic0.app")
    .with_identity(identity)
    .build()?;

agent.fetch_root_key().await?;  // Only needed for local replica

let dbms_canister_id = Principal::from_text("rrkah-fqaaa-aaaaa-aaaaq-cai").unwrap();
let client = IcDbmsAgentClient::new(&agent, dbms_canister_id);

// Use the client
let users = client.select::<User>(User::table_name(), query, None).await??;
}

IcDbmsPocketIcClient

For integration tests using PocketIC:

#![allow(unused)]
fn main() {
use ic_dbms_client::prelude::{IcDbmsPocketIcClient, Client as _};
use pocket_ic::nonblocking::PocketIc;
use candid::Principal;

let pic = PocketIc::new().await;
// ... setup canister ...

let client = IcDbmsPocketIcClient::new(
    canister_id,
    caller_principal,  // The principal making calls
    &pic
);

// Use the client in tests
let users = client.select::<User>(User::table_name(), query, None).await??;
}

Installation

Add ic-dbms-client to your Cargo.toml:

For canister development (inter-canister calls):

[dependencies]
ic-dbms-client = "0.11"

For external applications:

[dependencies]
ic-dbms-client = { version = "0.11", features = ["ic-agent"] }

For integration tests:

[dev-dependencies]
ic-dbms-client = { version = "0.11", features = ["pocket-ic"] }

For SQL endpoints: enable the sql feature, together with any other feature you need:

[dependencies]
ic-dbms-client = { version = "0.11", features = ["sql"] }

The Client Trait

All clients implement the Client trait, providing a consistent API:

#![allow(unused)]
fn main() {
// Simplified: every method returns
// `impl Future<Output = IcDbmsCanisterClientResult<IcDbmsResult<T>>>`.
pub trait Client {
    fn principal(&self) -> Principal;

    // CRUD Operations
    async fn insert<T: TableSchema>(
        &self,
        table: &str,
        record: T::Insert,
        tx: Option<TransactionId>,
    ) -> IcDbmsCanisterClientResult<IcDbmsResult<()>>;
    async fn select<T: TableSchema>(
        &self,
        table: &str,
        query: Query,
        tx: Option<TransactionId>,
    ) -> IcDbmsCanisterClientResult<IcDbmsResult<Vec<T::Record>>>;
    async fn select_raw(
        &self,
        table: &str,
        query: Query,
        tx: Option<TransactionId>,
    ) -> IcDbmsCanisterClientResult<IcDbmsResult<SelectOutput>>;
    async fn aggregate<T: TableSchema>(
        &self,
        table: &str,
        query: Query,
        aggregates: Vec<AggregateFunction>,
        tx: Option<TransactionId>,
    ) -> IcDbmsCanisterClientResult<IcDbmsResult<Vec<AggregatedRow>>>;
    async fn update<T: TableSchema>(
        &self,
        table: &str,
        patch: T::Update,
        tx: Option<TransactionId>,
    ) -> IcDbmsCanisterClientResult<IcDbmsResult<u64>>;
    async fn delete<T: TableSchema>(
        &self,
        table: &str,
        behaviour: DeleteBehavior,
        filter: Option<Filter>,
        tx: Option<TransactionId>,
    ) -> IcDbmsCanisterClientResult<IcDbmsResult<u64>>;

    // Transactions
    async fn begin_transaction(&self) -> IcDbmsCanisterClientResult<IcDbmsResult<TransactionId>>;
    async fn commit(&self, tx: TransactionId) -> IcDbmsCanisterClientResult<IcDbmsResult<()>>;
    async fn rollback(&self, tx: TransactionId) -> IcDbmsCanisterClientResult<IcDbmsResult<()>>;

    // Access control
    async fn acl_grant(&self, grant: AclGrant) -> IcDbmsCanisterClientResult<IcDbmsResult<()>>;
    async fn acl_revoke(&self, grant: AclGrant) -> IcDbmsCanisterClientResult<IcDbmsResult<()>>;
    async fn acl_list(&self) -> IcDbmsCanisterClientResult<IcDbmsResult<Vec<AclGrant>>>;
    async fn my_permissions(&self) -> IcDbmsCanisterClientResult<IcDbmsResult<Vec<AclGrant>>>;

    // Schema Migrations
    async fn has_drift(&self) -> IcDbmsCanisterClientResult<IcDbmsResult<bool>>;
    async fn pending_migrations(
        &self,
    ) -> IcDbmsCanisterClientResult<IcDbmsResult<Vec<MigrationOp>>>;
    async fn migrate(
        &self,
        policy: MigrationPolicy,
    ) -> IcDbmsCanisterClientResult<IcDbmsResult<()>>;

    // SQL (requires the `sql` feature)
    async fn sql(
        &self,
        query: &str,
        params: Vec<Value>,
        tx: Option<TransactionId>,
    ) -> IcDbmsCanisterClientResult<IcDbmsResult<SqlResult>>;
    async fn sql_query(
        &self,
        query: &str,
        params: Vec<Value>,
        tx: Option<TransactionId>,
    ) -> IcDbmsCanisterClientResult<IcDbmsResult<SqlResult>>;
}
}

Note the double Result:

  • Outer Result: Network/communication errors
  • Inner Result: Business logic errors (IcDbmsError)

Operations

Insert

#![allow(unused)]
fn main() {
use ic_dbms_client::prelude::Client as _;
use my_schema::{User, UserInsertRequest};

let user = UserInsertRequest {
    id: 1.into(),
    name: "Alice".into(),
    email: "alice@example.com".into(),
};

// Without transaction
client.insert::<User>(User::table_name(), user, None).await??;

// With transaction
client.insert::<User>(User::table_name(), user, Some(tx_id)).await??;
}

Select

#![allow(unused)]
fn main() {
use ic_dbms_api::prelude::*;

// Select all
let query = Query::builder().all().build();
let users: Vec<UserRecord> = client
    .select::<User>(User::table_name(), query, None)
    .await??;

// Select with filter
let query = Query::builder()
    .and_where(Filter::eq("status", Value::Text("active".into())))
    .order_by_desc("created_at")
    .limit(10)
    .build();
let users = client.select::<User>(User::table_name(), query, None).await??;
}

Untyped Select

All three client implementations expose select_raw(table, query, transaction_id) for the shared select endpoint. It returns SelectOutput, without requiring a record type: Raw for a single-table query or Joined when the query has joins. This replaces the previous vector return type; use as_raw() to access single-table rows or as_joined() to access shared join columns and value rows. Both accessors return None for the other variant.

#![allow(unused)]
fn main() {
use ic_dbms_api::prelude::{Query, SelectOutput};
use ic_dbms_client::prelude::Client as _;

let result: SelectOutput = client
    .select_raw("users", Query::builder().all().build(), None)
    .await??;
for row in result.iter() {
    for (column, value) in row.iter() {
        println!("{name}: {value:?}", name = column.name);
    }
}

let query = Query::builder()
    .all()
    .inner_join("posts", "users.id", "posts.user")
    .build();
let result = client.select_raw("users", query, None).await??;
if let Some(joined) = result.as_joined() {
    // Qualify names when both tables have an id column.
    let index = joined.column_index("posts.id").expect("posts.id column");
    for values in &joined.rows {
        println!("Post: {id:?}", id = values[index]);
    }
}
}

len() and is_empty() report row counts for either variant. The shared iter() borrows column-value pairs without cloning or expanding joined metadata. Joined results retain columns even when empty; empty raw results contain no column metadata. See the engine’s join query documentation for query construction and semantics.

Aggregate

Aggregate queries dispatch to the per-table aggregate_<table> endpoint generated by DbmsCanister. The pipeline (WHERE -> DISTINCT -> GROUP BY -> aggregate computation -> HAVING -> ORDER BY -> OFFSET/LIMIT) is described in the Query API reference.

#![allow(unused)]
fn main() {
use ic_dbms_api::prelude::{AggregateFunction, AggregatedValue, Filter, Query, Uint64, Value};

// COUNT(*) of all rows
let result = client
    .aggregate::<User>(
        User::table_name(),
        Query::default(),
        vec![AggregateFunction::Count(None)],
        None,
    )
    .await??;
assert!(matches!(result[0].values[0], AggregatedValue::Count(_)));

// GROUP BY + HAVING: rows per role, only roles with more than 5 users
let query = Query::builder()
    .group_by(&["role"])
    .having(Filter::gt("agg0", Value::Uint64(Uint64(5))))
    .order_by_desc("agg0")
    .build();
let result = client
    .aggregate::<User>(
        User::table_name(),
        query,
        vec![AggregateFunction::Count(None)],
        None,
    )
    .await??;
}

HAVING and ORDER BY reference aggregate outputs by their positional name agg{N} (agg0 is the first aggregate, agg1 the second, …). They may also reference any column listed in group_by.

Update

#![allow(unused)]
fn main() {
use my_schema::UserUpdateRequest;

let update = UserUpdateRequest {
    email: Some("new@example.com".into()),
    where_clause: Some(Filter::eq("id", Value::Uint32(1.into()))),
    ..Default::default()
};

let affected_rows: u64 = client
    .update::<User>(User::table_name(), update, None)
    .await??;
}

Delete

#![allow(unused)]
fn main() {
use ic_dbms_api::prelude::DeleteBehavior;

// Delete with filter
let deleted: u64 = client
    .delete::<User>(
        User::table_name(),
        DeleteBehavior::Restrict,
        Some(Filter::eq("id", Value::Uint32(1.into()))),
        None
    )
    .await??;

// Delete all (be careful!)
let deleted: u64 = client
    .delete::<User>(
        User::table_name(),
        DeleteBehavior::Cascade,
        None,  // No filter = all records
        None
    )
    .await??;
}

Transactions

#![allow(unused)]
fn main() {
// Begin transaction
let tx_id = client.begin_transaction().await??;

// Perform operations
client.insert::<User>(User::table_name(), user1, Some(tx_id)).await??;
client.insert::<User>(User::table_name(), user2, Some(tx_id)).await??;

// Commit or rollback
match some_condition {
    true => client.commit(tx_id).await??,
    false => client.rollback(tx_id).await??,
}
}

Schema Migrations

Three admin-gated methods inspect and apply schema drift. The Candid endpoints behind them (has_drift query, pending_migrations query, migrate update) are emitted by #[derive(DbmsCanister)]. See the IC migrations guide for the upgrade workflow.

#![allow(unused)]
fn main() {
use ic_dbms_api::prelude::{MigrationOp, MigrationPolicy};

// O(1) once cached on the canister side. True iff a migration is needed.
let drift: bool = client.has_drift().await??;
if !drift {
    return Ok(());
}

// Plan without applying. Always recomputes; safe to call during drift.
let plan: Vec<MigrationOp> = client.pending_migrations().await??;
for op in &plan {
    eprintln!("  {op:?}");
}

// Apply. Refuses DropTable / DropColumn unless allow_destructive is set.
client.migrate(MigrationPolicy::default()).await??;

// Equivalent to:
client
    .migrate(MigrationPolicy { allow_destructive: false })
    .await??;
}

migrate is idempotent — when there is no drift, the call is a cheap no-op.

Access Control

#![allow(unused)]
fn main() {
use candid::Principal;
use ic_dbms_api::prelude::{AclGrant, AclPermission};

// Grant admin
let operator = Principal::from_text("aaaaa-aa").unwrap();
client.acl_grant(AclGrant::admin(operator)).await??;

// Let a service insert into one table only
client
    .acl_grant(AclGrant::table(service, AclPermission::Insert, "users"))
    .await??;

// List grants
for grant in client.acl_list().await?? {
    println!("{} -> {} on {:?}", grant.principal, grant.permission, grant.table);
}

// Revoke admin (fails with AclError::LastAdmin for the last one)
client.acl_revoke(AclGrant::admin(operator)).await??;

// Own grants, allowed for everyone
let mine = client.my_permissions().await??;
}

SQL

With the sql feature, sql runs any statement through the update endpoint and sql_query runs a SELECT through the query endpoint:

#![allow(unused)]
fn main() {
let rows = client
    .sql_query("SELECT name FROM users WHERE id = ?", vec![Value::from(1u32)], None)
    .await??;
}

See the SQL guide for results, transactions and permissions.


Error Handling

Client operations return nested Results:

#![allow(unused)]
fn main() {
use ic_dbms_api::prelude::{DbmsError, IcDbmsError, QueryError};

// Full error handling
match client.insert::<User>(User::table_name(), user, None).await {
    Ok(Ok(())) => {
        println!("Insert successful");
    }
    Ok(Err(db_error)) => {
        // Database error (validation, constraint violation, etc.)
        match db_error {
            IcDbmsError::Dbms(DbmsError::Query(QueryError::PrimaryKeyConflict)) => {
                println!("User with this ID already exists");
            }
            IcDbmsError::Dbms(DbmsError::Validation(msg)) => {
                println!("Validation failed: {}", msg);
            }
            _ => println!("Database error: {:?}", db_error),
        }
    }
    Err(call_error) => {
        // Network/canister call error
        println!("Call failed: {:?}", call_error);
    }
}
}

Simplified with ??:

#![allow(unused)]
fn main() {
// Propagate both error types
client.insert::<User>(User::table_name(), user, None).await??;
}

Examples

Inter-Canister Communication

A backend canister calling the database canister:

#![allow(unused)]
fn main() {
use candid::Principal;
use ic_cdk::update;
use ic_dbms_client::prelude::{Client as _, IcDbmsCanisterClient};

const DBMS_CANISTER: &str = "rrkah-fqaaa-aaaaa-aaaaq-cai";

#[update]
async fn create_user(name: String, email: String) -> Result<u32, String> {
    let client = IcDbmsCanisterClient::new(Principal::from_text(DBMS_CANISTER).unwrap());

    let user_id = generate_id();
    let user = UserInsertRequest {
        id: user_id.into(),
        name: name.into(),
        email: email.into(),
    };

    client
        .insert::<User>(User::table_name(), user, None)
        .await
        .map_err(|e| format!("Call failed: {:?}", e))?
        .map_err(|e| format!("Insert failed: {:?}", e))?;

    Ok(user_id)
}

#[update]
async fn get_users() -> Result<Vec<UserRecord>, String> {
    let client = IcDbmsCanisterClient::new(Principal::from_text(DBMS_CANISTER).unwrap());

    let query = Query::builder().all().build();

    client
        .select::<User>(User::table_name(), query, None)
        .await
        .map_err(|e| format!("Call failed: {:?}", e))?
        .map_err(|e| format!("Query failed: {:?}", e))
}
}

External Application

A CLI tool or backend service:

use candid::Principal;
use ic_agent::Agent;
use ic_agent::identity::BasicIdentity;
use ic_dbms_api::prelude::{Query, TableSchema as _};
use ic_dbms_client::prelude::{Client as _, IcDbmsAgentClient};
use my_schema::User;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load identity from PEM file
    let identity = BasicIdentity::from_pem_file("identity.pem")?;

    // Create agent
    let agent = Agent::builder()
        .with_url("https://ic0.app")
        .with_identity(identity)
        .build()?;

    // For local development, fetch root key
    // agent.fetch_root_key().await?;

    let canister_id = Principal::from_text("rrkah-fqaaa-aaaaa-aaaaq-cai")?;
    let client = IcDbmsAgentClient::new(&agent, canister_id);

    // List all users
    let query = Query::builder().all().build();
    let users = client
        .select::<User>(User::table_name(), query, None)
        .await??;

    // Record fields are `Option` because a query can select a subset of columns.
    for user in users {
        println!("User: {:?} ({:?})", user.name, user.email);
    }

    Ok(())
}

Integration Testing

Testing with PocketIC:

#![allow(unused)]
fn main() {
use candid::{Principal, encode_one};
use ic_dbms_client::prelude::{Client as _, IcDbmsPocketIcClient};
use pocket_ic::nonblocking::PocketIc;

#[tokio::test]
async fn test_user_crud() {
    // Setup PocketIC
    let pic = PocketIc::new().await;

    // Create and install canister
    let canister_id = pic.create_canister().await;
    pic.add_cycles(canister_id, 2_000_000_000_000).await;

    let wasm = std::fs::read("path/to/canister.wasm").unwrap();
    let init_args = IcDbmsCanisterArgs::Init(IcDbmsCanisterInitArgs {
        allowed_principals: Some(vec![admin_principal]),
    });

    pic.install_canister(canister_id, wasm, encode_one(init_args).unwrap(), None)
        .await;

    // Create client
    let client = IcDbmsPocketIcClient::new(canister_id, admin_principal, &pic);

    // Test insert
    let user = UserInsertRequest {
        id: 1.into(),
        name: "Test User".into(),
        email: "test@example.com".into(),
    };
    client
        .insert::<User>(User::table_name(), user, None)
        .await
        .unwrap()
        .unwrap();

    // Test select
    let query = Query::builder().all().build();
    let users = client
        .select::<User>(User::table_name(), query, None)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(users.len(), 1);
    // Record fields are `Option` because a query can select a subset of columns.
    assert_eq!(users[0].name.as_ref().unwrap().as_str(), "Test User");

    // Test update
    let update = UserUpdateRequest {
        name: Some("Updated User".into()),
        where_clause: Some(Filter::eq("id", Value::Uint32(1.into()))),
        ..Default::default()
    };
    let affected = client
        .update::<User>(User::table_name(), update, None)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(affected, 1);

    // Test delete
    let deleted = client
        .delete::<User>(
            User::table_name(),
            DeleteBehavior::Restrict,
            Some(Filter::eq("id", Value::Uint32(1.into()))),
            None,
        )
        .await
        .unwrap()
        .unwrap();
    assert_eq!(deleted, 1);

    // Verify deletion
    let users = client
        .select::<User>(User::table_name(), Query::builder().all().build(), None)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(users.len(), 0);
}
}