mirror of
https://github.com/clockworklabs/SpacetimeDB.git
synced 2026-06-27 08:18:48 -04:00
eef0e423a8
# Description of Changes
Adds support for primary keys to procedural views in rust and typescript
modules. Now clients can receive update events when subscribed to such
views.
```rust
#[spacetimedb::view(accessor = my_players, public, primary_key = id)]
pub fn my_players(ctx: &spacetimedb::ViewContext) -> Vec<Player> {
ctx.db.players().owner().filter(ctx.sender()).collect()
}
```
```ts
const Player = t.row('Player', {
id: t.u64().primaryKey(),
owner: t.identity().index('btree'),
name: t.string(),
});
export const my_players = spacetimedb.view(
{ public: true },
t.array(players.rowType),
ctx => Array.from(ctx.db.players.owner.filter(ctx.sender))
);
```
In rust, a view's primary key is declared within the `#[view]` macro,
whereas in typescript it is declared at the column/row level as it is
for tables. I could have made it a view level attribute for typescript
as well, but since primary keys are already row-level attributes in
typescript, I just kept that as is.
Note, care must be taken to ensure that the view never returns duplicate
primary keys, or else it will fail which will currently result in the
transaction that triggered the view refresh to be rolled back. Better
error handling for this exact scenario will be added in a separate
follow up patch.
## Alternative Considered: #[primary_key] attribute on `SpacetimeType`s
in Rust
This would be equivalent to what we do in typescript.
# API and ABI breaking changes
None, although adding a primary key to an existing view will require a
client update.
# Expected complexity level and risk
3
# Testing
Compile-time failure scenarios:
- [x] Primary key on non-existent column
- [x] Primary key doesn't reference custom accessor name (rust)
- [x] Multiple primary key columns specified (typescript)
- [x] Primary keys must be `FilterableValue`s
SDK tests (rust sdk, rust and ts modules):
- [x] `OnUpdate`
- [x] `OnUpdate` is sender-scoped
- [X] Can join on primary key columns
Smoketests:
- [x] Modifying primary key columns breaks clients (auto-migrations)