SpacetimeDB icon indicating copy to clipboard operation
SpacetimeDB copied to clipboard

Fiddle with unique constraint `find` trait bounds so that `&str` can filter a column of type `String`

Open bfops opened this issue 9 months ago • 0 comments

DoD: the following module compiles:

use spacetimedb::{ReducerContext, SpacetimeType, Table};

#[spacetimedb::table(name = player, public)]
pub struct Player {
    #[primary_key]
    #[auto_inc]
    player_id: u64,
    #[unique]
    username: String,
    level: u32,
    class: Class,
}

#[derive(SpacetimeType)]
pub enum Class {
    Fighter,
    Caster,
    Medic,
}

pub fn find_player_by_name(ctx: &ReducerContext, name: &str) -> Option<Player> {
    ctx.db.player().username().find(name)
}

pub fn find_player_by_id(ctx: &ReducerContext, player_id: u64) -> Option<Player> {
    ctx.db.player().player_id().find(player_id)
}

pub fn update_player(ctx: &ReducerContext, player: Player) {
    ctx.db.player().player_id().update(player);
}

Currently it errors with:

error[E0277]: the trait bound `&str: std::borrow::Borrow<std::string::String>` is not satisfied
   --> src/lib.rs:22:37
    |
22  |     ctx.db.player().username().find(name)
    |                                ---- ^^^^ the trait `std::borrow::Borrow<std::string::String>` is not implemented for `&str`
    |                                |
    |                                required by a bound introduced by this call
    |
    = help: the trait `std::borrow::Borrow<str>` is implemented for `std::string::String`
note: required by a bound in `spacetimedb::UniqueColumn::<Tbl, ColType, Col>::find`
   --> /home/phoebe/clockworklabs/SpacetimeDB/crates/bindings/src/table.rs:306:38
    |
306 |     pub fn find(&self, col_val: impl Borrow<ColType>) -> Option<Tbl::Row> {
    |                                      ^^^^^^^^^^^^^^^ required by this bound in `UniqueColumn::<Tbl, ColType, Col>::find`

bfops avatar Mar 07 '25 18:03 bfops