docs/docs/00200-core-concepts/00600-clients/00500-rust-reference.md
The SpacetimeDB client SDK for Rust contains all the tools you need to build native clients for SpacetimeDB modules using Rust.
Before diving into the reference, you may want to review:
| Name | Description |
|---|---|
| Project setup | Configure a Rust crate to use the SpacetimeDB Rust client SDK. |
| Generate module bindings | Use the SpacetimeDB CLI to generate module-specific types and interfaces. |
DbConnection type | A connection to a remote database. |
DbContext trait | Methods for interacting with the remote database. Implemented by DbConnection and various event context types. |
EventContext type | DbContext available in row callbacks. |
ReducerEventContext type | DbContext available in reducer callbacks. |
SubscriptionEventContext type | DbContext available in subscription-related callbacks. |
ErrorContext type | DbContext available in error-related callbacks. |
| Query Builder API | Type-safe query builder for typed subscription queries. |
| Access the client cache | Make local queries against subscribed rows, and register row callbacks to run when subscribed rows change. |
| Observe and invoke reducers | Send requests to the database to run reducers, and register callbacks to run when notified of reducers. |
| Identify a client | Types for identifying users and client connections. |
First, create a new project using cargo new and add the SpacetimeDB SDK to your dependencies:
cargo add spacetimedb_sdk
Each SpacetimeDB client depends on some bindings specific to your module. Create a module_bindings directory in your project's src directory and generate the Rust interface files using the Spacetime CLI. From your project directory, run:
mkdir -p src/module_bindings
spacetime generate --lang rust \
--out-dir src/module_bindings \
--module-path PATH-TO-MODULE-DIRECTORY
Replace PATH-TO-MODULE-DIRECTORY with the path to your SpacetimeDB module.
Declare a mod for the bindings in your client's src/main.rs:
mod module_bindings;
DbConnectionmodule_bindings::DbConnection
A connection to a remote database is represented by the module_bindings::DbConnection type. This type is generated per-module, and contains information about the types, tables and reducers defined by your module.
| Name | Description |
|---|---|
| Connect to a database | Construct a DbConnection. |
| Advance the connection | Poll the DbConnection, or set up a background worker to run it. |
| Access tables and reducers | Access subscribed rows in the client cache, request reducer invocations, and register callbacks. |
impl DbConnection {
fn builder() -> DbConnectionBuilder;
}
Construct a DbConnection by calling DbConnection::builder() and chaining configuration methods, then calling .build(). You must at least specify with_uri, to supply the URI of the SpacetimeDB to which you published your module, and with_database_name, to supply the human-readable SpacetimeDB domain name or the raw Identity which identifies the database.
| Name | Description |
|---|---|
with_uri method | Set the URI of the SpacetimeDB instance which hosts the remote database. |
with_database_name method | Set the name or Identity of the remote database. |
with_confirmed_reads method | Enable or disable confirmed reads. |
on_connect callback | Register a callback to run when the connection is successfully established. |
on_connect_error callback | Register a callback to run if the connection is rejected or the host is unreachable. |
on_disconnect callback | Register a callback to run when the connection ends. |
with_token method | Supply a token to authenticate with the remote database. |
build method | Finalize configuration and connect. |
with_uriimpl DbConnectionBuilder {
fn with_uri(self, uri: impl TryInto<Uri>) -> Self;
}
Configure the URI of the SpacetimeDB instance or cluster which hosts the remote database containing the module.
with_database_nameimpl DbConnectionBuilder {
fn with_database_name(self, name_or_identity: impl ToString) -> Self;
}
Configure the SpacetimeDB domain name or Identity of the remote database which identifies it within the SpacetimeDB instance or cluster.
with_confirmed_readsimpl DbConnectionBuilder {
fn with_confirmed_reads(self, confirmed: bool) -> Self;
}
Configure the connection to request confirmed reads.
When enabled, the server will send query results only after they are confirmed to be durable, i.e. persisted to disk on one or more replicas depending on the replication settings of the database. When set to false, the server will send results as soon as transactions are committed in memory.
If this method is not called, the server chooses the default.
on_connectimpl DbConnectionBuilder {
fn on_connect(self, callback: impl FnOnce(&DbConnection, Identity, &str)) -> DbConnectionBuilder;
}
Chain a call to .on_connect(callback) to your builder to register a callback to run when your new DbConnection successfully initiates its connection to the remote database. The callback accepts three arguments: a reference to the DbConnection, the Identity by which SpacetimeDB identifies this connection, and a private access token which can be saved and later passed to with_token to authenticate the same user in future connections.
This interface may change in an upcoming release as we rework SpacetimeDB's authentication model.
on_connect_errorimpl DbConnectionBuilder {
fn on_connect_error(
self,
callback: impl FnOnce(&ErrorContext, spacetimedb_sdk::Error),
) -> DbConnectionBuilder;
}
Chain a call to .on_connect_error(callback) to your builder to register a callback to run when your connection fails.
A known bug in the SpacetimeDB Rust client SDK currently causes this callback never to be invoked. on_disconnect callbacks are invoked instead.
on_disconnectimpl DbConnectionBuilder {
fn on_disconnect(
self,
callback: impl FnOnce(&ErrorContext, Option<spacetimedb_sdk::Error>),
) -> DbConnectionBuilder;
}
Chain a call to .on_disconnect(callback) to your builder to register a callback to run when your DbConnection disconnects from the remote database, either as a result of a call to disconnect or due to an error.
with_tokenimpl DbConnectionBuilder {
fn with_token(self, token: Option<impl ToString>>) -> Self;
}
Chain a call to .with_token(token) to your builder to provide an OpenID Connect compliant JSON Web Token to authenticate with, or to explicitly select an anonymous connection. If this method is not called or None is passed, SpacetimeDB will generate a new Identity and sign a new private access token for the connection.
buildimpl DbConnectionBuilder {
fn build(self) -> Result<DbConnection, spacetimedb_sdk::Error>;
}
After configuring the connection and registering callbacks, attempt to open the connection.
In the interest of supporting a wide variety of client applications with different execution strategies, the SpacetimeDB SDK allows you to choose when the DbConnection spends compute time and processes messages. If you do not arrange for the connection to advance by calling one of these methods, the DbConnection will never advance, and no callbacks will ever be invoked.
| Name | Description |
|---|---|
run_threaded method | Spawn a thread to process messages in the background. |
run_async method | Process messages in an async task. |
frame_tick method | Process messages on the main thread without blocking. |
run_threadedimpl DbConnection {
fn run_threaded(&self) -> std::thread::JoinHandle<()>;
}
run_threaded spawns a thread which will continuously advance the connection, sleeping when there is no work to do. The thread will panic if the connection disconnects erroneously, or return if it disconnects as a result of a call to disconnect.
run_asyncimpl DbConnection {
async fn run_async(&self) -> Result<(), spacetimedb_sdk::Error>;
}
run_async will continuously advance the connection, await-ing when there is no work to do. The task will return an Err if the connection disconnects erroneously, or return Ok(()) if it disconnects as a result of a call to disconnect.
frame_tickimpl DbConnection {
fn frame_tick(&self) -> Result<(), spacetimedb_sdk::Error>;
}
frame_tick will advance the connection until no work remains, then return rather than blocking or await-ing. Games might arrange for this message to be called every frame. frame_tick returns Ok if the connection remains active afterwards, or Err if the connection disconnected before or during the call.
dbstruct DbConnection {
pub db: RemoteTables,
/* other members */
}
The db field of the DbConnection provides access to the subscribed view of the remote database's tables. See Access the client cache.
reducersstruct DbConnection {
pub reducers: RemoteReducers,
/* other members */
}
The reducers field of the DbConnection provides access to reducers exposed by the remote module. See Observe and invoke reducers.
DbContexttrait spacetimedb_sdk::DbContext {
/* methods */
}
DbConnection, EventContext, ReducerEventContext, SubscriptionEventContext and ErrorContext all implement DbContext. DbContext has methods for inspecting and configuring your connection to the remote database, including ctx.db(), a trait-generic alternative to reading the .db property on a concrete-typed context object.
The DbContext trait is implemented by connections and contexts to every module. This means that its DbView and Reducers are associated types.
| Name | Description |
|---|---|
RemoteDbContext trait | Module-specific DbContext extension trait with associated types bound. |
db method | Trait-generic alternative to the db field of DbConnection. |
reducers method | Trait-generic alternative to the reducers field of DbConnection. |
disconnect method | End the connection. |
| Subscribe to queries | Register subscription queries to receive updates about matching rows. |
| Read connection metadata | Access the connection's Identity and ConnectionId |
RemoteDbContexttrait module_bindings::RemoteDbContext
: spacetimedb_sdk::DbContext</* Associated type constraints */> {}
Each module's module_bindings exports a trait RemoteDbContext which extends DbContext, with the associated types DbView and Reducers bound to the types defined for that module. This can be more convenient when creating functions that can be called from any callback for a specific module, but which access the database or invoke reducers, and so must know the type of the DbView or Reducers.
dbtrait DbContext {
fn db(&self) -> &Self::DbView;
}
When operating in trait-generic contexts, it is necessary to call the ctx.db() method, rather than accessing the ctx.db field, as Rust traits cannot expose fields.
fn print_users(ctx: &impl RemoteDbContext) {
for user in ctx.db().user().iter() {
println!("{}", user.name);
}
}
reducerstrait DbContext {
fn reducerrs(&self) -> &Self::Reducers;
}
When operating in trait-generic contexts, it is necessary to call the ctx.reducers() method, rather than accessing the ctx.reducers field, as Rust traits cannot expose fields.
fn call_say_hello(ctx: &impl RemoteDbContext) {
ctx.reducers.say_hello();
}
disconnecttrait DbContext {
fn disconnect(&self) -> spacetimedb_sdk::Result<()>;
}
Gracefully close the DbConnection. Returns an Err if the connection is already disconnected.
| Name | Description |
|---|---|
SubscriptionBuilder type | Builder-pattern constructor to register subscribed queries. |
TypedSubscriptionBuilder type | Builder for typed query subscriptions. |
SubscriptionHandle type | Manage an active subscription. |
SubscriptionBuilderspacetimedb_sdk::SubscriptionBuilder
| Name | Description |
|---|---|
ctx.subscription_builder() constructor | Begin configuring a new subscription. |
on_applied callback | Register a callback to run when matching rows become available. |
on_error callback | Register a callback to run if the subscription fails. |
subscribe method | Finish configuration and subscribe to one or more queries. |
add_query method | Build a typed subscription query without writing query strings. |
subscribe_to_all_tables method | Convenience method to subscribe to the entire database. |
ctx.subscription_builder()trait DbContext {
fn subscription_builder(&self) -> SubscriptionBuilder;
}
Subscribe to queries by calling ctx.subscription_builder() and chaining configuration methods, then calling .subscribe(queries).
on_appliedimpl SubscriptionBuilder {
fn on_applied(self, callback: impl FnOnce(&SubscriptionEventContext)) -> Self;
}
Register a callback to run when the subscription is applied and the matching rows are inserted into the client cache.
on_errorimpl SubscriptionBuilder {
fn on_error(self, callback: impl FnOnce(&ErrorContext, spacetimedb_sdk::Error)) -> Self;
}
Register a callback to run if the subscription is rejected or unexpectedly terminated by the server. This is most frequently caused by passing an invalid query to subscribe.
subscribeimpl SubscriptionBuilder {
fn subscribe(self, queries: impl IntoQueries) -> SubscriptionHandle;
}
Subscribe to a set of queries. queries should be a string or an array, vec or slice of strings.
See the SpacetimeDB SQL Reference for information on the queries SpacetimeDB supports as subscriptions.
For typed query subscriptions, use add_query.
add_queryimpl<M: SpacetimeModule> SubscriptionBuilder<M> {
fn add_query<T>(
self,
build: impl Fn(M::QueryBuilder) -> impl Query<T>,
) -> TypedSubscriptionBuilder<M>;
}
Start a typed query subscription. Once a typed query is added, continue with typed queries on TypedSubscriptionBuilder and finish with subscribe().
let handle = conn
.subscription_builder()
.add_query(|q| q.from.user())
.add_query(|q| q.from.message())
.subscribe();
subscribe_to_all_tablesimpl SubscriptionBuilder {
fn subscribe_to_all_tables(self);
}
Subscribe to all rows from all public tables. This method is provided as a convenience for simple clients. The subscription initiated by subscribe_to_all_tables cannot be canceled after it is initiated. You should subscribe to specific queries if you need fine-grained control over the lifecycle of your subscriptions.
TypedSubscriptionBuilderTypedSubscriptionBuilder<M>
| Name | Description |
|---|---|
add_query method | Add another typed query to the same subscription. |
subscribe method | Subscribe to all typed queries added so far. |
add_query (TypedSubscriptionBuilder)impl<M: SpacetimeModule> TypedSubscriptionBuilder<M> {
fn add_query<T>(
self,
build: impl Fn(M::QueryBuilder) -> impl Query<T>,
) -> Self;
}
Add another typed query. This keeps all added queries grouped under one returned SubscriptionHandle.
subscribe (TypedSubscriptionBuilder)impl<M: SpacetimeModule> TypedSubscriptionBuilder<M> {
fn subscribe(self) -> M::SubscriptionHandle;
}
Subscribe to the set of typed queries that were added to the builder.
The Rust SDK provides a type-safe query builder for subscriptions. You use it through subscription_builder().add_query(...).
Typed query builders are created from generated table accessors under QueryBuilder.from.
let handle = conn
.subscription_builder()
.add_query(|q| q.from.user())
.subscribe();
where / filterRust uses the raw identifier form r#where(...) because where is a keyword. filter(...) is an alias. Chaining multiple r#where/filter calls combines conditions with logical AND.
// All users
q.from.user()
// Filtered users
q.from.user().r#where(|u| u.online.eq(true))
q.from.user().filter(|u| u.name.ne("Anonymous"))
// Chained filters (AND semantics)
q.from
.user()
.r#where(|u| u.score.gte(1000u64))
.filter(|u| u.level.gte(10u32))
| Operator | Description | Example |
|---|---|---|
eq | Equal to | u.online.eq(true) |
ne | Not equal to | u.name.ne("BOT") |
lt | Less than | u.level.lt(10u32) |
lte | Less than or equal to | u.level.lte(10u32) |
gt | Greater than | u.score.gt(1000u64) |
gte | Greater than or equal to | u.score.gte(1000u64) |
Combine conditions with and, or, and not:
q.from.user().r#where(|u| u.level.gte(5u32).and(u.level.lt(10u32)))
q.from.user().r#where(|u| u.online.eq(true).or(u.name.eq("Admin")))
q.from.user().r#where(|u| u.banned.eq(true).not())
Semijoins match rows across two tables and return rows from one side:
left_semijoin(...) returns rows from the left side that match at least one row on the right.right_semijoin(...) returns rows from the right side that match at least one row on the left.IxCols) and compares one indexed column from each side with eq.let handle = conn
.subscription_builder()
.add_query(|q| {
q.from
.player()
.r#where(|p| p.score.gte(1000u64))
.left_semijoin(q.from.player_level(), |p, pl| p.id.eq(pl.player_id))
.r#where(|p| p.online.eq(true))
})
.add_query(|q| {
q.from
.player()
.r#where(|p| p.score.gte(1000u64))
.right_semijoin(q.from.player_level(), |p, pl| p.id.eq(pl.player_id))
.r#where(|pl| pl.level.gte(10u32))
})
.subscribe();
add_query accepts a builder function returning impl Query<T>. You can add multiple typed queries and subscribe once.
let handle = conn
.subscription_builder()
.add_query(|q| q.from.user().r#where(|u| u.online.eq(true)))
.add_query(|q| q.from.message().r#where(|m| m.channel_id.eq(1u32)))
.subscribe();
SubscriptionHandlemodule_bindings::SubscriptionHandle
A SubscriptionHandle represents a subscribed query or a group of subscribed queries.
The SubscriptionHandle does not contain or provide access to the subscribed rows. Subscribed rows of all subscriptions by a connection are contained within that connection's ctx.db. See Access the client cache.
| Name | Description |
|---|---|
is_ended method | Determine whether the subscription has ended. |
is_active method | Determine whether the subscription is active and its matching rows are present in the client cache. |
unsubscribe method | Discard a subscription. |
unsubscribe_then method | Discard a subscription, and register a callback to run when its matching rows are removed from the client cache. |
is_endedimpl SubscriptionHandle {
fn is_ended(&self) -> bool;
}
Returns true if this subscription has been terminated due to an unsubscribe call or an error.
is_activeimpl SubscriptionHandle {
fn is_active(&self) -> bool;
}
Returns true if this subscription has been applied and has not yet been unsubscribed.
unsubscribeimpl SubscriptionHandle {
fn unsubscribe(&self) -> Result<(), spacetimedb_sdk::Error>;
}
Terminate this subscription, causing matching rows to be removed from the client cache. Any rows removed from the client cache this way will have on_delete callbacks run for them.
Unsubscribing is an asynchronous operation. Matching rows are not removed from the client cache immediately. Use unsubscribe_then to run a callback once the unsubscribe operation is completed.
Returns an error if the subscription has already ended, either due to a previous call to unsubscribe or unsubscribe_then, or due to an error.
unsubscribe_thenimpl SubscriptionHandle {
fn unsubscribe_then(
self,
on_end: impl FnOnce(&SubscriptionEventContext),
) -> Result<(), spacetimedb_sdk::Error>;
}
Terminate this subscription, and run the on_end callback when the subscription is ended and its matching rows are removed from the client cache. Any rows removed from the client cache this way will have on_delete callbacks run for them.
Returns an error if the subscription has already ended, either due to a previous call to unsubscribe or unsubscribe_then, or due to an error.
identitytrait DbContext {
fn identity(&self) -> Identity;
}
Get the Identity with which SpacetimeDB identifies the connection. This method may panic if the connection was initiated anonymously and the newly-generated Identity has not yet been received, i.e. if called before the on_connect callback is invoked.
try_identitytrait DbContext {
fn try_identity(&self) -> Option<Identity>;
}
Like DbContext::identity, but returns None instead of panicking if the Identity is not yet available.
connection_idtrait DbContext {
fn connection_id(&self) -> ConnectionId;
}
Get the ConnectionId with which SpacetimeDB identifies the connection.
is_activetrait DbContext {
fn is_active(&self) -> bool;
}
true if the connection has not yet disconnected. Note that a connection is_active when it is constructed, before its on_connect callback is invoked.
EventContextmodule_bindings::EventContext
An EventContext is a DbContext augmented with a field event: Event. EventContexts are passed as the first argument to row callbacks on_insert, on_delete and on_update.
| Name | Description |
|---|---|
event field | Enum describing the cause of the current row callback. |
db field | Provides access to the client cache. |
reducers field | Allows requesting reducers run on the remote database. |
Event enum | Possible events which can cause a row callback to be invoked. |
eventstruct EventContext {
pub event: spacetimedb_sdk::Event<module_bindings::Reducer>,
/* other fields */
}
The Event contained in the EventContext describes what happened to cause the current row callback to be invoked.
dbstruct EventContext {
pub db: RemoteTables,
/* other members */
}
The db field of the context provides access to the subscribed view of the remote database's tables. See Access the client cache.
reducersstruct EventContext {
pub reducers: RemoteReducers,
/* other members */
}
The reducers field of the context provides access to reducers exposed by the remote module. See Observe and invoke reducers.
Eventspacetimedb_sdk::Event<module_bindings::Reducer>
| Name | Description |
|---|---|
Reducer variant | A reducer ran in the remote database. |
SubscribeApplied variant | A new subscription was applied to the client cache. |
UnsubscribeApplied variant | A previous subscription was removed from the client cache after a call to unsubscribe. |
SubscribeError variant | A previous subscription was removed from the client cache due to an error. |
UnknownTransaction variant | A transaction ran in the remote database, but was not attributed to a known reducer. |
ReducerEvent struct | Metadata about a reducer run. Contained in Event::Reducer and ReducerEventContext. |
Status enum | Completion status of a reducer run. |
Reducer enum | Module-specific generated enum with a variant for each reducer defined by the module. |
Reducerspacetimedb_sdk::Event::Reducer(spacetimedb_sdk::ReducerEvent<module_bindings::Reducer>)
Event when we are notified that a reducer ran in the remote database. The ReducerEvent contains metadata about the reducer run, including its arguments and termination Status.
This event is passed to row callbacks resulting from modifications by the reducer.
SubscribeAppliedspacetimedb_sdk::Event::SubscribeApplied
Event when our subscription is applied and its rows are inserted into the client cache.
This event is passed to row on_insert callbacks resulting from the new subscription.
UnsubscribeAppliedspacetimedb_sdk::Event::UnsubscribeApplied
Event when our subscription is removed after a call to SubscriptionHandle::unsubscribe or SubscriptionHandle::unsubscribe_then and its matching rows are deleted from the client cache.
This event is passed to row on_delete callbacks resulting from the subscription ending.
SubscribeErrorspacetimedb_sdk::Event::SubscribeError(spacetimedb_sdk::Error)
Event when a subscription ends unexpectedly due to an error.
This event is passed to row on_delete callbacks resulting from the subscription ending.
UnknownTransactionEvent when we are notified of a transaction in the remote database which we cannot associate with a known reducer. This may be an ad-hoc SQL query or a reducer for which we do not have bindings.
This event is passed to row callbacks resulting from modifications by the transaction.
ReducerEventspacetimedb_sdk::ReducerEvent<module_bindings::Reducer>
A ReducerEvent contains metadata about a reducer run.
struct spacetimedb_sdk::ReducerEvent<R> {
/// The time at which the reducer was invoked.
timestamp: SystemTime,
/// Whether the reducer committed, was aborted due to insufficient energy, or failed with an error message.
status: Status,
/// The `Identity` of the SpacetimeDB actor which invoked the reducer.
caller_identity: Identity,
/// The `ConnectionId` of the SpacetimeDB actor which invoked the reducer,
/// or `None` for scheduled reducers.
caller_connection_id: Option<ConnectionId>,
/// The amount of energy consumed by the reducer run, in eV.
/// (Not literal eV, but our SpacetimeDB energy unit eV.)
///
/// May be `None` if the module is configured not to broadcast energy consumed.
energy_consumed: Option<u128>,
/// The `Reducer` enum defined by the `module_bindings`, which encodes which reducer ran and its arguments.
reducer: R,
// ...private fields
}
Statusspacetimedb_sdk::Status
| Name | Description |
|---|---|
Committed variant | The reducer ran successfully. |
Failed variant | The reducer errored. |
OutOfEnergy variant | The reducer was aborted due to insufficient energy. |
Committedspacetimedb_sdk::Status::Committed
The reducer returned successfully and its changes were committed into the database state. An Event::Reducer passed to a row callback must have this status in its ReducerEvent.
Failedspacetimedb_sdk::Status::Failed(Box<str>)
The reducer returned an error, panicked, or threw an exception. The enum payload is the stringified error message. Formatting of the error message is unstable and subject to change, so clients should use it only as a human-readable diagnostic, and in particular should not attempt to parse the message.
OutOfEnergyThe reducer was aborted due to insufficient energy balance of the module owner.
Reducermodule_bindings::Reducer
The module bindings contains an enum Reducer with a variant for each reducer defined by the module. Each variant has a payload containing the arguments to the reducer.
ReducerEventContextA ReducerEventContext is a DbContext augmented with a field event: ReducerEvent. ReducerEventContexts are passed as the first argument to reducer callbacks.
| Name | Description |
|---|---|
event field | ReducerEvent containing reducer metadata. |
db field | Provides access to the client cache. |
reducers field | Allows requesting reducers run on the remote database. |
eventstruct ReducerEventContext {
pub event: spacetimedb_sdk::ReducerEvent<module_bindings::Reducer>,
/* other fields */
}
The ReducerEvent contained in the ReducerEventContext has metadata about the reducer which ran.
dbstruct ReducerEventContext {
pub db: RemoteTables,
/* other members */
}
The db field of the context provides access to the subscribed view of the remote database's tables. See Access the client cache.
reducersstruct ReducerEventContext {
pub reducers: RemoteReducers,
/* other members */
}
The reducers field of the context provides access to reducers exposed by the remote module. See Observe and invoke reducers.
SubscriptionEventContextA SubscriptionEventContext is a DbContext. Unlike the other context types, SubscriptionEventContext doesn't have an event field. SubscriptionEventContexts are passed to subscription on_applied and unsubscribe_then callbacks.
| Name | Description |
|---|---|
db field | Provides access to the client cache. |
reducers field | Allows requesting reducers run on the remote database. |
dbstruct SubscriptionEventContext {
pub db: RemoteTables,
/* other members */
}
The db field of the context provides access to the subscribed view of the remote database's tables. See Access the client cache.
reducersstruct SubscriptionEventContext {
pub reducers: RemoteReducers,
/* other members */
}
The reducers field of the context provides access to reducers exposed by the remote module. See Observe and invoke reducers.
ErrorContextAn ErrorContext is a DbContext augmented with a field event: spacetimedb_sdk::Error. ErrorContexts are to connections' on_disconnect and on_connect_error callbacks, and to subscriptions' on_error callbacks.
| Name | Description |
|---|---|
event field | The error which caused the current error callback. |
db field | Provides access to the client cache. |
reducers field | Allows requesting reducers run on the remote database. |
eventstruct ErrorContext {
pub event: spacetimedb_sdk::Error,
/* other fields */
}
dbstruct ErrorContext {
pub db: RemoteTables,
/* other members */
}
The db field of the context provides access to the subscribed view of the remote database's tables. See Access the client cache.
reducersstruct ErrorContext {
pub reducers: RemoteReducers,
/* other members */
}
The reducers field of the context provides access to reducers exposed by the remote module. See Observe and invoke reducers.
All DbContext implementors, including DbConnection and EventContext, have fields .db, which in turn has methods for accessing tables in the client cache. The trait method DbContext::db(&self) can also be used in contexts with an impl DbContext rather than a concrete-typed EventContext or DbConnection.
Each table defined by a module has an accessor method, whose name is the table name converted to snake_case, on this .db field. The methods are defined via extension traits, which rustc or your IDE should help you identify and import where necessary. The table accessor methods return table handles, which implement Table, may implement TableWithPrimaryKey, and have methods for searching by unique index.
| Name | Description |
|---|---|
Table trait | Provides access to subscribed rows of a specific table within the client cache. |
TableWithPrimaryKey trait | Extension trait for tables which have a column designated as a primary key. |
| Unique constraint index access | Seek a subscribed row by the value in its unique or primary key column. |
| BTree index access | Not supported. |
Tablespacetimedb_sdk::Table
Implemented by all table handles.
| Name | Description |
|---|---|
Row associated type | The type of rows in the table. |
count method | The number of subscribed rows in the table. |
iter method | Iterate over all subscribed rows in the table. |
on_insert callback | Register a callback to run whenever a row is inserted into the client cache. |
on_delete callback | Register a callback to run whenever a row is deleted from the client cache. |
Rowtrait spacetimedb_sdk::Table {
type Table::Row;
}
The type of rows in the table.
counttrait spacetimedb_sdk::Table {
fn count(&self) -> u64;
}
Returns the number of rows of this table resident in the client cache, i.e. the total number which match any subscribed query.
itertrait spacetimedb_sdk::Table {
fn iter(&self) -> impl Iterator<Item = Self::Row>;
}
An iterator over all the subscribed rows in the client cache, i.e. those which match any subscribed query.
on_inserttrait spacetimedb_sdk::Table {
type InsertCallbackId;
fn on_insert(&self, callback: impl FnMut(&EventContext, &Self::Row)) -> Self::InsertCallbackId;
fn remove_on_insert(&self, callback: Self::InsertCallbackId);
}
The on_insert callback runs whenever a new row is inserted into the client cache, either when applying a subscription or being notified of a transaction. The passed EventContext contains an Event which can identify the change which caused the insertion, and also allows the callback to interact with the connection, inspect the client cache and invoke reducers.
Registering an on_insert callback returns a callback id, which can later be passed to remove_on_insert to cancel the callback. Newly registered or canceled callbacks do not take effect until the following event.
on_deletetrait spacetimedb_sdk::Table {
type DeleteCallbackId;
fn on_delete(&self, callback: impl FnMut(&EventContext, &Self::Row)) -> Self::DeleteCallbackId;
fn remove_on_delete(&self, callback: Self::DeleteCallbackId);
}
The on_delete callback runs whenever a previously-resident row is deleted from the client cache. Registering an on_delete callback returns a callback id, which can later be passed to remove_on_delete to cancel the callback. Newly registered or canceled callbacks do not take effect until the following event.
TableWithPrimaryKeyspacetimedb_sdk::TableWithPrimaryKey
Implemented for handles whose rows have a known primary key, including query builder views with inferred primary keys.
| Name | Description |
|---|---|
on_update callback | Register a callback to run whenever a subscribed row is replaced with a new version. |
on_updatetrait spacetimedb_sdk::TableWithPrimaryKey {
type UpdateCallbackId;
fn on_update(&self, callback: impl FnMut(&EventContext, &Self::Row, &Self::Row)) -> Self::UpdateCallbackId;
fn remove_on_update(&self, callback: Self::UpdateCallbackId);
}
The on_update callback runs whenever an already-resident row in the client cache is updated, i.e. replaced with a new row that has the same primary key. Registering an on_update callback returns a callback id, which can later be passed to remove_on_update to cancel the callback. Newly registered or canceled callbacks do not take effect until the following event.
This also applies to query builder views over tables with primary keys.
For each unique constraint on a table, its table handle has a method whose name is the unique column name which returns a unique index handle. The unique index handle has a method .find(desired_val: &Col) -> Option<Row>, where Col is the type of the column, and Row the type of rows. If a row with desired_val in the unique column is resident in the client cache, .find returns it.
The SpacetimeDB Rust client SDK does not support non-unique BTree indexes.
All DbContext implementors, including DbConnection and EventContext, have fields .reducers, which in turn has methods for invoking reducers defined by the module and registering callbacks on it. The trait method DbContext::reducers(&self) can also be used in contexts with an impl DbContext rather than a concrete-typed EventContext or DbConnection.
Each reducer defined by the module has three methods on the .reducers:
set_name. This requests that the module run the reducer.on_, like on_set_name. This registers a callback to run whenever we are notified that the reducer ran, including successfully committed runs and runs we requested which failed. This method returns a callback id, which can be passed to the callback remove method.remove_on_, like remove_on_set_name. This cancels a callback previously registered via the callback registration method.Identityspacetimedb_sdk::Identity
A unique public identifier for a client connected to a database.
ConnectionIdspacetimedb_sdk::ConnectionId
An opaque identifier for a client connection to a database, intended to differentiate between connections from the same Identity.